I recently started programming mobile applications with flutter. I have a problem with reading a file. In practice, while the app is running I write a string to a text file (and I can also read it correctly). My need is to read from this file every time the app is accessed; therefore, in the initState () function I call the readContent () function but I get the following message: "FileSystemException: Cannot open file, path = '/var/mobile/Containers/Data/Application/F8A5A202-45C9-47F6-93C9-E4BAE2AF3C7E/Documents/counter.txt' (OS Error: No such file or directory, errno = 2)". Could you help me?
This is my code:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print("directory path: "+directory.path);
return directory.path;
}
Future<io.File> get _localFile async {
final path = await _localPath;
return io.File('$path/counter.txt');
}
String datas = "";
//questa funzione viene richiamata all'avvio della schermata e serve per leggere il valore del flag checkSendingReport dal file
@override
void initState() {
super.initState();
readContent().then((String value) {
print(value);
setState(() {
String data = value;
List data_file_split = data.split("#");
checkSendingReport = data_file_split[1];
check_sending_report = data_file_split[1];
});
});
}
//Questa funzione serve per leggere il file locale scritto in precenza
Future<String> readContent() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
//Returning the contents of the file
return contents;
} catch (e) {
// If encountering an error, return
return 'Error! '+e.toString();
}
}
//questa funzione serve per scrivere il file locale
Future<io.File> writeContent(datetime) async {
final file = await _localFile;
//Setto a true la variabile flag check_sending_report
check_sending_report = true;
//Creo la stringa da inserire nel file: composta da datetime#flag
String data_file = datetime + "#" + check_sending_report.toString();
// Write the file
return file.writeAsString(data_file);
}