I am currently experimenting with the File class to write String objects to a .txt file that is locally stored in the device. I've already managed to create a .txt file and write in it with the writeAsString method. I can also append String objects to it by passing FileMode.append as the optional mode parameter. However, I bumped into a question: What if I wanted to delete some lines or an amount of characters of that same text file? Is there a way to do that?
Here is the code I've written so far:
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
title: 'Reading and Writing Files',
home: FlutterDemo(),
),
);
}
class FlutterDemo extends StatefulWidget {
@override
_FlutterDemoState createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
_createAndWrite(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/test1.txt');
await file.writeAsString(text);
}
_writeAgain(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/test1.txt');
await file.writeAsString(text, mode: FileMode.append);
}
Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/test1.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
print(text);
return text;
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Reading and Writing Files')),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
onPressed: (){
_createAndWrite("this is working");
},
child: Text(
"Create and write",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
height: 60,
minWidth: 80,
),
FlatButton(
onPressed: _read,
child: Text(
"Print on\n the console",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
height: 60,
minWidth: 80,
),
FlatButton(
onPressed: (){
_writeAgain(" you added something new");
},
child: Text(
"Create and write\n / Write again",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
height: 60,
minWidth: 80,
),
],
),
),
);
}
}