读取文件返回null



我有一个在文件中写入颜色的页面,名为"colors.txt"然后关闭该页,当再次打开该页时,将读取该文件并将其内容(String)打印在屏幕上。

这是处理读和写的类:

class Pathfinder {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/colors.txt');
}
Future<File> writeColor(String color) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$color');
}
Future<String> readColor() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return contents;
} catch (e) {
// If encountering an error, return 0
return "Error while reading colors";
}
}
}

在页面关闭之前,颜色已经用writeColor保存,我们只需要读取文件并打印其内容。我是这样读取color的:

void initState() {
super.initState();
String colorRead;
() async {
pf = new Pathfinder();
colorRead = await pf.readColor();
}();
print("Color in initState: " + colorRead.toString());
}

问题是colorRead总是null。我已经尝试了.then().whenCompleted(),但没有任何改变。

所以我的疑问是:我是否没有以正确的方式等待读取操作,或者由于某些原因,在页面关闭时删除了文件?

我认为如果文件不存在,那么readColor应该抛出一个错误。

编辑:writeColor如何命名:

Color bannerColor;
//some code
await pf.writeColor(bannerColor.value.toRadixString(16));
void initState() {
super.initState();
String colorRead;
() async {
pf = new Pathfinder();
colorRead = await pf.readColor();
}();
print("Color in initState: " + colorRead.toString()); /// << this will execute before the async code in the function is executed
}

由于async/await的工作方式,它是空的。print语句将在匿名异步函数完成执行之前被调用。如果你在函数内部打印,你应该看到颜色,如果其他一切都工作正常。