gpt4 book ai didi

dart - 下面的Flutter读写文件文档有没有浪费实现?

转载 作者:IT王子 更新时间:2023-10-29 07:10:08 26 4
gpt4 key购买 nike

来自 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每次他们被调用时都会吸气。

我的问题是:

这不是有点浪费吗?等待_localFile不是更好吗?在 CounterStorage 的构造函数中,并将其存储在类成员中,而不是获取 _localPath_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 被解析,这是我的偏好。在上面的例子中,没有,所以我更喜欢:

创建一个staticasync方法来创建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 的过程可能在每个应用程序中发生一次。

关于dart - 下面的Flutter读写文件文档有没有浪费实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com