首页 > 解决方案 > 读取文件返回 null Flutter

问题描述

我有一个在文件上写入颜色的页面,称为“colors.txt”。然后页面关闭,当它再次打开时,将读取该文件并将其内容(String)打印在屏幕上。

这是处理读取和写入的类:

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));

标签: flutterdartfile-io

解决方案


  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 的工作方式,它为空。print 语句将在匿名异步函数完成执行之前被调用。如果您在函数内部打印,如果其他一切正常,您应该会看到颜色。


推荐阅读