【发布时间】:2018-07-09 22:15:32
【问题描述】:
来自flutter doc:
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If we encounter an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
readCounter() 和 writeCounter() 在每次被调用时都会调用 _localPath getter。
我的问题是:
这不是有点浪费吗?在CounterStorage 的构造函数中等待_localFile,并将其存储在类成员中,而不是每次都获取_localPath 和_localPath 不是更好吗?
有人可以建议这样的实现吗?
【问题讨论】:
-
你不能让构造函数异步。通过在第一次解析
_local*变量查找的结果时保存它们,实现可能会更有效率。