我需要将文本写入“ .txt”文件中,并将其保存在变量中,然后将其提供给Text
中的TextField
。
想法是将用户输入内容写入“ .txt”文件,以便他可以在需要时读取自己在TextField
上写的内容。
一切正常,当我读取文件时,它具有正确的内容,但是当我将其存储在变量中以供使用时Text(var_name...)
,我在屏幕上看到的是“'Future'的实例”。
我知道这个问题源于对异步和未来的不正确处理,但我想真正理解为什么它不起作用。
这是我的代码:
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_;
}
请写下完整的答案,我尝试了很多视频,论坛...不仅仅是告诉我做var str= _MyRead().then((value) => value);
也许可以作为答案,但是请再写2行,因为我想了解为什么这行不通。
我从开发者官方文档中获取了代码。
答案 0 :(得分:2)
您正在同步的渲染过程(有状态/无状态窗口小部件的生成功能)中使用异步值。您不能只将Future
中的String
放在String
的位置。它不会工作。为什么?由于它的类型不同,因此您需要特殊的方法才能将变量从一种类型转换为另一种类型。
在这种情况下,您可能希望在构建过程中将此Future
异步转换为String
。您可以为此使用FutureBuilder
。
return FutureBuilder<String>(
future: _myRead,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else {
return Text('awaiting the future');
}
},
);
如果您不将此Future
转换为要渲染的String
,它将只是一个Instance of Future
。
答案 1 :(得分:1)
如果要渲染需要时间(异步)的内容,则应使用FutureBuilder
FutureBuilder(
future:_myRead,
builder: (ctx,snapshot) {
if(snapshot.connectionState == connectionState.waiting) {
return // your waiting Widget Ex: CircularLoadingIndicator();
} else if (snapshot.hasData) {
return Text(snapshot.data.toString()); // toString() is just to be safe
} else { //probably an error occured
return Text('Something went wrong ...');
}