读取文件 returns null Flutter

read file returns null Flutter

我有一个页面在文件上写了一个颜色,叫做“colors.txt”。然后页面关闭,当它再次打开时将读取这个文件及其内容(String) 打印在屏幕上。

这是处理读写的 class :

class Pathfinder {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

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

  Future<File> writeColor(String color) async {
    final file = await _localFile;
    // Write the file
    return file.writeAsString('$color');
  }

  Future<String> readColor() async {
    try {
      final file = await _localFile;

      // Read the file
      final contents = await file.readAsString();

      return contents;
    } catch (e) {
      // If encountering an error, return 0
      return "Error while reading colors";
    }
  }
}

在页面关闭之前,颜色已经用writeColor保存了,我们只需要读取文件并打印它的内容即可。 这就是我阅读颜色的方式:

void initState() {
    super.initState();
    String colorRead;
    () async {
      pf = new Pathfinder();
      colorRead = await pf.readColor();
    }();
    print("Color in initState: " + colorRead.toString());
  }

问题是 colorRead 总是 null。我已经尝试了 .then().whenCompleted() 但没有任何改变。

所以我的疑问是: 我是不是没有以正确的方式等待读取操作,或者由于某些原因,当页面关闭时文件被删除了?

我认为如果文件不存在,那么 readColor 应该会抛出一个错误。

编辑:如何调用 writeColor

Color bannerColor;
//some code
await pf.writeColor(bannerColor.value.toRadixString(16));
  void initState() {
    super.initState();
    String colorRead;
    () async {
      pf = new Pathfinder();
      colorRead = await pf.readColor();
    }();
    print("Color in initState: " + colorRead.toString()); /// << this will execute before the async code in the function is executed
  }

由于 async/await 的工作原理,它为空。打印语句将在匿名异步函数完成执行之前被调用。如果您在函数内部打印,如果其他一切正常,您应该会看到颜色。