How do you read text from a file and write text to a file?
I\'ve been learning about how to read and write text to and from a file. I found another question about readin
Add the following plugin in pubspec.yaml
:
dependencies:
path_provider: ^0.4.1
Update the version number to whatever is current.
And import it in your code.
import 'package:path_provider/path_provider.dart';
You also have to import dart:io
to use the File
class.
import 'dart:io';
_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}
Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}
join(directory.path, 'my_file.txt')
but you need to import 'package:path/path.dart'
.