Flutter/Dart - 调用一个 Future<String> 的函数...但只需要 return 一个 String

Flutter/Dart - calling a function that is a Future<String> ... but needs to return only a String

我有一个调用 Firestore 以提取数据值的异步函数。我在之前的 post 中得到了很多帮助...学到了很多东西...并希望从一个更清晰的问题开始。所以我有以下功能

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

此功能逻辑有效...我可以将 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),
      ),

那个 setList 变量不是字符串。当我打印它时 [print(setList.toString()] 它显示为 Future String.

的一个实例

我尝试使用:var setList = await getSetList();,但在等待时显示错误。

任何想法表示赞赏。

你不能在非异步函数中使用 await,这意味着使用

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.

希望我的设置状态没有任何语法错误。

https://docs.flutter.io/flutter/widgets/State/setState.html

https://docs.flutter.io/flutter/widgets/State/initState.html