Reputation: 2679
I have a text file in memory that I open using File.readAsString().. This extracts the text from it and saves it as a String. This is given to a TextField() so that changes can be made to this text.
How do I effectively save these changes back to the original file?
Here is my code so far. Everything works as is, the file opens and the text in it is displayed in the TextField. But I dont know how to save the changes back to file..
class _NoteEditScreenState extends State<NoteEditScreen> {
TextEditingController _controller;
String startingText = '';
String fileName;
@override
void initState() {
super.initState();
getTextFromFile().whenComplete(() {
//when we read the string, extract lines from it
lines = lineSplitter.convert(startingText);
setState(() {
_controller = TextEditingController(text: startingText);
});
});
fileName = widget.txtPath.split('/').last;
}
Future getTextFromFile() async {
final file = File(widget.txtPath);
//read the file
String contents = await file.readAsString();
startingText = contents;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(fileName),
backgroundColor: Colors.teal,
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: (){
showSearch(context: context, delegate: TextSearch(lines));
},
),
],
),
body: Center(
child: Container(
padding: EdgeInsets.all(5.0),
//height: 50.0,
child: TextField(
maxLines: null,
controller: _controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal),
//borderRadius: BorderRadius.all(Radius.circular(20.0))
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
//borderRadius: BorderRadius.all(Radius.circular(20.0))
),
),
),
),
),
The way I see it happening is to delete the old file and create a new file with same name.. Is this the best way of doing this? Or can you guys suggest a better way?
Upvotes: 0
Views: 1229
Reputation: 3539
To write to a file, you can use
yourFile.writeAsString(contents)
or yourFile.writeAsStringSync(contents)
.
Use writeAsString
if you don't want to wait for the file to write completely or if you don't want to block app execution, or use writeAsStringSync
if you want to prevent the app from continuing until it's done writing.
Upvotes: 1