假设我有一个SingleChildScrollView
,它的内容是从一个文件中读取的:
singleChildScrollView(
padding: EdgeInsets.all(8.0),
child: nw Text(
getTextFromFile(), //<---read from file
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Future<String> getTextFromFile() async {
return getFileData("test.txt");
}
我收到以下错误:
The argument type 'Future<String>' can't be assigned to the parameter
type 'String'.
如何解决这个问题?
最佳答案
使用 FutureBuilder 应该可以解决您的问题。我修改了您的代码,以便您了解如何使用它。 initialData
不是必需的。
@override
Widget build(BuildContext context) {
return new FutureBuilder(
future: getTextFromFile(),
initialData: "Loading text..",
builder: (BuildContext context, AsyncSnapshot<String> text) {
return new SingleChildScrollView(
padding: new EdgeInsets.all(8.0),
child: new Text(
text.data,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
});
}
Future<String> getFileData(String path) async {
return await new Future(() => "test text");
}
Future<String> getTextFromFile() async {
return getFileData("test.txt");
}
}
关于dart - 如何将future<>分配给flutter中的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49764905/