Search code examples
flutterflutter-futurebuilderdart-asyncflutter-stateflutter-future

How to listen for state changes inside a FutureBuilder widget and reflect the state change?


to demonstrate the problem, let me write down some code for a FutureBuilder.

FutureBuilder(future: _myFuture, builder: (context, snapshot) {
    if(snapshot.hasData) {

        // !!!! IMPORTANT !!!
        // Pay attention to the _isFirstText variable below  

        return SizedBox(
                 child: _isFirstText ? Text(snapshot.data.firstText) : Text(snapshot.data.secondText),
               );  
    }
 
    if(snapshot.connectionState == ConnectionState.isWaiting) {
        return Text('Waiting!');
    }
 
    return Text('Error');
}),  

As I have mentioned in a comment in the above code, pay attention to the _isFirstText variable. Suppose that is a state variable. Inside the future builder, how do I get the correct return value that corresponds to the isFirstText state variable change.

I also came across this stack overflow post but could not get the code to work.
I also came across a widget called StatefulBuilder, but I can not figure out to where in my FutureBuilder I should use it.

Can someone please help?


Solution

  • If you want to listen to ongoing changes you can use a Streambuilder. Streams are not only for serverside changes but can also be used locally.

    You can build a Stream yourself like this :

    StreamController myStreamController = StreamController<int>();
    

    To send a new event through this controller you can do

    myStreamController.sink.add(newValue);
    

    You can then listen to changes like this:

      @override
      Widget build(BuildContext context) {
        return StreamBuilder<int>(
            stream: myStreamController.stream,
            builder: (context, snapshot) {
              final value = snapshot.data;
    
              return Text(value!.toString());
      }
    
    

    If you want to learn more check this Video: https://youtu.be/nQBpOIHE4eE

    Let me know if this helped.