I want user to enter text in textfield. When user clicks the fab, the text is written to a file as a new line(appending). I want my app to read the contents of the file and show each line as a listtile in a listview, below the input textfield. When user enters a new text, that should appear in the listview instantaneously.
I was able to do up to writing the text to the file. But how to read the file and display its contents? Should I use streambuilder?. Below is the code I did till now:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Path Provider',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Path Provider', storage: FileStorage(),),
);
}
}
class FileStorage {
Future<String> get _localPath async {
final directory = await getTemporaryDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/file.txt');
}
void readFile() {
/* What to do? */
}
Future<Null> writeFile(String text) async {
final file = await _localFile;
IOSink sink = file.openWrite(mode: FileMode.append);
sink.add(utf8.encode('$text'));
await sink.flush();
await sink.close();
}
}
class MyHomePage extends StatefulWidget {
final FileStorage storage;
MyHomePage({Key key, this.title, this.storage}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final myController = TextEditingController();
@override
void dispose() {
// TODO: implement dispose
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(
title: new Text('Testing'),
),
body: new Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: new TextField(
controller: myController,
decoration: new InputDecoration(
hintText: 'Enter the text',
),
),
),
// StreamBuilder(
// stream: widget.storage.readCounter().asStream(),
// )
],
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.save_alt),
onPressed: () {
widget.storage.writeFile(myController.text);
},
),
);
}
}