0

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?

CodeR_Ax20
  • 91
  • 1
  • 8
  • Does this answer your question? [Flutter StreamBuilder vs FutureBuilder](https://stackoverflow.com/questions/50844519/flutter-streambuilder-vs-futurebuilder) – staticVoidMan Dec 16 '21 at 11:34
  • @staticVoidMan thank you for the response. According to the answer, streams hold an ongoing connection to the server and updates the UI depending on the changes from the server right? But I do not want to listen for changes from the server side. I want to listen for the changes of a local state variable. Do you know how to do this? Thanks! – CodeR_Ax20 Dec 16 '21 at 11:37

2 Answers2

2

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.

Christian
  • 834
  • 7
  • 18
0

You can use ValueNotifier variables and use notifyListeners() to update a specific parts of your code Like this:

ValueListenableBuilder and use that ValueNotifier variable and listen to that.

gtr Developer
  • 2,369
  • 16
  • 12