How to listen to the changes and rebuild the widget in flutter using provider packge?

Issue

The problem i am facing is,
I am connecting my ui to backend with websocket using subscribe method(graphql client). That means there is a connection between my ui and backend. I am storing the data i got from backend in the local storage
From the local storage, i am getting that data,

Whenever i receive the data from backend it should be reflected in the ui automatically. For reflecting change in ui, i am using state management provider package.What should i do to make my widget rebuild on listening to the changes i had made using provider package;

Solution

class MyNotifier extends ChangeNotifier {
   bool _listenableValue = false;
   bool get listenableValue => _listenableValue

   MyNotifier.instance();

   void setValue(){
      _listenableValue = !_listenableValue;
      notifyListeners();
   }
}


...

@override
Widget build(BuildContext context) {
   return ChangeNotifierProvider<MyNotifier>(
       create: (context) => MyNotifier.instance(),
       builder: (context, child){
          return Column(
             children: [
                StaticWidget(),
                //This text widget will rebuild when value is changed
                Selector<MyNotifier, bool>(
                  selector: (_, notifier) => notifier.listenableValue,
                  builder: (_, value, __) => Text('$value');
                ),
                //Change value with button
                IconButton(
                  icon: //icon
                  onPressed: (){
                    context.read<MyNotifier>().setValue();
                  },
                );
             ]
          );
       }
   );
}

Don’ t use Consumer. Consumer will rebuild all widgets when a data changed. This is the bad situation for performance.
Selector is the best in my opinion.

Answered By – blokberg

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *