rob*_*win 2 asynchronous future dart flutter google-cloud-firestore
我有一个异步函数,它调用 Firestore 以获取数据值。我在之前的一篇文章中得到了很多帮助……学到了很多东西……我想重新开始,希望能提出一个更清晰的问题。所以我有以下功能
Future<String> getSetList () async {
DocumentReference set01DocRef = Firestore.instance.collection('sets').document('SET01');
var snapshot = await set01DocRef.get();
songList = snapshot['songs']; //works, get expected text value from FS
return songList;
}
Run Code Online (Sandbox Code Playgroud)
这个函数逻辑有效......我可以将songList var(字符串var)打印()到控制台,我看到来自Firestore的值。当我尝试调用该函数时:
@override
Widget build(BuildContext context) {
var setList = getSetList();
print('In widget: ' + setList.toString()); //shows as instance of Future<String>
//List<String> items = setList.split('|');
List<String> items = ['Red','White','Blue'];
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
Run Code Online (Sandbox Code Playgroud)
该 setList 变量不是字符串。当我打印它 [print(setList.toString()] 时,它显示为 Future String 的一个实例。
我尝试使用:var setList = await getSetList();但是在等待上显示错误。
任何想法表示赞赏。
你什么时候需要打电话给未来?
您始终可以创建一个 tmp 变量并尝试加载它。您不能将期货随机放入构建过程中。您需要获取数据,然后调用 setState 以在视图发生更改时通知小部件。
String _setList = null;
//initState called when the widget is mounted.
void initState() {
super.initState();
if(_setList == null){
getSetList().then(
(String s) => setState(() {_setList = s;})
);
}
}
@override
Widget build(BuildContext context) {
String setList = _setList;
print('In widget: ' + setList.toString()); //shows as instance of Future<String>
if(setList != null){
//List<String> items = setList.split('|');
List<String> items = ['Red','White','Blue'];
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
} else { return const CircularProgressIndicator(); }
//Create a progress circle.
Run Code Online (Sandbox Code Playgroud)
我希望我的设置状态没有任何语法错误。
https://docs.flutter.io/flutter/widgets/State/setState.html
https://docs.flutter.io/flutter/widgets/State/initState.html
| 归档时间: |
|
| 查看次数: |
15182 次 |
| 最近记录: |