flutter - 读取文件返回 null Flutter
问题描述
我有一个在文件上写入颜色的页面,称为“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
,我们只需要读取文件并打印其内容即可。这就是我阅读颜色的方式:
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 语句将在匿名异步函数完成执行之前被调用。如果您在函数内部打印,如果其他一切正常,您应该会看到颜色。
推荐阅读
- sql - 如何对 SQL Server 表中的列进行最佳匹配?
- php - 在 html 行中显示 mysql 汇总数据,而在 php 中没有单独的列
- ajax - 动态模态不加载数据
- android - onDraw 外的画布高度
- android - 使用 volly 在参数中将数组作为 json 发布
- java - 如何在 Java 中以正确的方式将 List<> 项作为 POST 数据发送?
- c# - 无需用户交互即可发送 Xamarin.Forms(仅限 Android)SMS
- c++ - 找到 $number 然后用 $number+1 替换它?
- python - 如何删除 sys.path.append("../") 但没有得到 ImportError: No module named XXX
- javascript - 如何使用 vue js 在谷歌地图中放置标记?