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

后端 未结 2 1831
醉酒成梦
醉酒成梦 2021-01-25 16:40

I have an async function that is calling out to Firestore to pull in a data value. I got a lot of help in a previous post...learned a lot...and wanted to start over with hopeful

相关标签:
2条回答
  • 2021-01-25 17:26

    When do you need to call the future?

    You can always create a tmp variable and try to load it. You cannot randomly put futures into the build process. You need to grab the data then call setState to notify the widget if the view has changed.

    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.
    

    I hope my set state does not have any sytax errors.

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

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

    0 讨论(0)
  • 2021-01-25 17:27

    you can't use await in a function that is not async, which means the use

    var setList = await getSetList();
    

    in your build function is wrong.

    0 讨论(0)
提交回复
热议问题