dart - 以下Flutter读/写文件文档是否有浪费的实现?
问题描述
来自颤振文档:
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()
调用getter。_localPath
我的问题是:
这不是有点浪费吗?等待_localFile
的构造函数中的CounterStorage
并将其存储在类成员中,而不是每次都获取_localPath
and不是更好吗?_localPath
有人可以建议这样的实现吗?
解决方案
这取决于您所说的浪费是什么意思,以及getApplicationDocumentsDirectory
.
例如,如果下次调用它时可以getApplicationDocumentsDirectory()
返回不同的路径(例如,如果新用户登录,可能 - 我不确定细节),那么这是完全正确的。
如果保证该值永远不会改变,则可以进一步优化,但显示优化可能不是示例文档的目标。如果你有兴趣,我能想到的两个想法是:
创建一个static final
字段:
class CounterStorage {
// Static fields in Dart are lazy; this won't get sent until used.
static final _localPath = getApplicationDocumentsDirectory().then((p) => p.path);
// ...
}
如果CounterStorage
有其他方法或字段无需等待_localPath
解决,这是我的偏好。在上面的例子中,没有,所以我更喜欢:
创建一个创建static
async
方法CounterStorage
import 'package:meta/meta.dart';
class CounterStorage {
// You could even combine this with the above example, and make this a
// static final field.
static Future<CounterStorage> resolve() async {
final localPath = await getApplicationDocumentsDirectory();
return new CounterStorage(new File(this.localPath));
}
final File _file;
// In a test you might want to use a temporary directory instead.
@visibleForTesting
CounterStorage(this._file);
Future<int> readCount() async {
try {
final contents = await _file.readAsString();
return int.parse(contents);
} catch (_) {
return 0;
}
}
}
这使得检索File
每个应用程序的过程可能发生一次。
推荐阅读
- python - Selenium 远程 webdriver 错误(连接被拒绝)
- powershell - 无法删除 Azure 恢复服务保管库
- docusignapi - Demo-Docusign Connect 通知不起作用
- php - jQuery 文件上传插件 https://blueimp.net
- regex - 为没有小数点和字母的千位分隔符定义正则表达式
- javascript - 在ajax post请求中传递第二个参数
- r - 无法使用 rtweet 包创建令牌
- c++ - 带有 cpptools 的 VSCode:使用 compile_commands.json 会导致错误的自动完成
- amazon-ec2 - 具有不同区域的 EC2 实例的 AWS ELB
- python-3.x - KeyError: ('url', 'text')