在构建方法 flutter 中调用异步函数

Mic*_*oss 4 dart dart-async flutter

我需要将文本写入“.txt”文件中,将其保存在变量中并将其赋予Text, 内的TextField. 这个想法是将用户输入写入“.txt”文件中,以便他可以在需要时在 .txt 上读取他所写的内容TextField

一切正常,当我读取文件时,它会获取正确的内容,但是当我将其存储在变量中以便Text(var_name...)很好地使用它时,我在屏幕上读到的是“‘未来’的实例”。

我知道这个问题来自于对异步和未来的错误处理,但我想真正理解为什么这不起作用。

这是我的代码:

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

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

Future<File> _write(String text, String filename) async {
final file = await _localBio;

// Write the file.
return file.writeAsString(text);
}

Future<String> _read() async {
  try {
    final file = await _localBio;
     String body = await file.readAsString();
  // Read the file.
    return body;
  } catch (e) {
  // If encountering an error, return 0.
    return "Can't read";
  }
}

Future<String>_MyRead() async {
 String read_ = await _read();
 print(read_);
 return read_;
}
Run Code Online (Sandbox Code Playgroud)

请写一个完整的答案,我尝试了很多视频、论坛...不要只是告诉我这样做var str= _MyRead().then((value) => value); 也许它可以是答案,但请再写 2 行,因为我想了解为什么这不起作用。我从开发官方文档中获取了代码。

小智 8

您在同步的渲染过程(有状态/无状态小部件的构建函数)中使用异步值。你不能只将 aFuture放入Stringa 的位置String。这是行不通的。为什么?因为它是不同的类型,并且您需要特殊的方法将变量从一种类型转换为另一种类型。

在这种情况下,您可能希望在构建过程中将其转换Future为异步。String您可以使用 aFutureBuilder来实现这一点。

return FutureBuilder<String>(
  future: _myRead,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data);
    } else {
      return Text('awaiting the future');
    }
  },
);
Run Code Online (Sandbox Code Playgroud)

如果你不将其转换Future为要渲染的 a String,那么它只是一个Instance of Future.