【问题标题】:Does the following Flutter reading / writing files document have wasteful implementation?以下Flutter读/写文件文档是否有浪费的实现?
【发布时间】: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* 变量查找的结果时保存它们,实现可能会更有效率。

标签: dart flutter


【解决方案1】:

这要看你说的浪费是什么意思,还有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 的过程可能发生一次。

【讨论】:

  • 该示例中 _file 何时实际设置?
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多