首页 > 解决方案 > 以下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并将其存储在类成员中,而不是每次都获取_localPathand不是更好吗?_localPath

有人可以建议这样的实现吗?

标签: dartflutter

解决方案


这取决于您所说的浪费是什么意思,以及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每个应用程序的过程可能发生一次。


推荐阅读