什么时候使用Dart私有的get函数而不使用backing字段



我将介绍这个例子https://docs.flutter.dev/cookbook/persistence/reading-writing-files

下面的类是用私有get函数定义的,但没有支持字段。它们是什么意思,什么时候有用?Esp._localPath和_localFile。

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
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}

本质上,写

Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}

实际上与编写类似的函数相同

Future<File> _localFile() async {
final path = await _localPath;
return File('$path/counter.txt');
}

我不认为有什么真正的区别,但我可能错了。只有访问方式不同。第一个需要写_localFile,第二个需要添加像_localFile()这样的括号。这取决于个人喜好。如果您希望在将来也编写setter,那么第一个表示法可能会很有用。

最新更新