0
votes

I am struggling with the following problem:

I built a list of widgets using StreamBuilder (and made it searchable). The widgets are Cards and inside them the user can make his selection and then push a button. Everything is (was) working just fine.

Then I wanted to add a little animation and make the Icon associated to the button an animated one. Now it is a mess, the StreamBuilder is in an infinite loop and I have also some problem on my list. If I comment out the animated icon and put in again the previous Icon ...everything starts to work fine again.

...
                child: FloatingActionButton(
                  onPressed: (){
                    addFood();
                    mealListState.getAcontroller(id).forward();
                  },
                  child:
//                    MyAddIcon(id),  //--> my animated Icon. It does not work
                  Icon(Icons.add),    //--> it works
....

I read that the problem is that adding States management (Unnecessary Widget Rebuilds While Using Selector (Provider) inside StreamBuilder) inside the stream mess things up and that you have to make the widget building the stream Stateful and set up the stream in the initState. I tried to follow this way but I need the context to build my card list, so I could follow the above hint just to read the data from db (firestore) and ...it is not enough

Could someone point me in the right direction or I have to leave the idea and move on?

Thanks

1

1 Answers

0
votes

If you need the context, you can try to listen to the the stream in the didChangeDependencies method of your State class. Use the Streamsubscription returned by stream.listen to cancel your subscription like so to avoid subsribing twice or even more times:

@override
didChangeDependencies() {
    final stream = Provider.of<MyStream>(context); // context available here.
    if (this.streamsubscription != null) {
        this.streamsubscription.cancel();
    }
    this.streamsubscription = stream.listen((value) {
    // your callback code here
    });
    super.didChangeDependencies(); // important
}