Search code examples
flutterdartdart-async

How do I use a FutureBuilder between two stateful widgets when the child waits for a parent's set state to complete?


I have a widget that uses a TabBar. The parent widget makes an http call that needs to be completed before the TabBar widgets can be drawn (they use the data). How do I enforce the TabBarView widgets to wait for the parent http call to be completed and for me to set the state variable which is then used in the TabBarView widgets. It seems like the solution is to use a FutureBuilder for all TabBar widgets, but how do those widgets know to wait for the parent to complete? Those widgets await the data of the parent.

Parent widget - make http call, set state variable x TabBarView widgets, wait for x. An error is being thrown because TB1 is being called before x is set unless I throw in some dummy data.

Parent Widget

  void initState() {
    x = await _getdata();
    setState(() => this.x = x);

  }

...

        TabBarView(
            controller: _tabController,
            children: [
              new TB1(x),
              new TB2(x),
              new TB3(x),
            ]
        )

Solution

  • You can conditionally build your widget

    DataType x = null;
    
    void initState() {
        _getdata().then((_x) {
            if (mounted){ // Just to be sure is safe to call setState, since _getdata is asynchronous
                setState(() => x = _x);
            }
        });    
    }
    
    Widget build(BuildContext context){
        // Loading
        if (x == null){
           return CircularProgressIndicator();
        }else{
            return TabBarView(...);
        }
    }