Search code examples
flutterdartproviderstate-management

what is ChangeNotifierProvider Multiprovider, Consumer in flutter


Hi everyone i am new to flutter. and iam trying to learn state management in flutter using provider. i have seen so many tutorials. but i didn't understand whats going on some poeples wrapping MaterialApp with ChangeNotifireProvider and some with MultiProvider. and also some peoples wrapping widgets with consumer to see changes. but some doing thing like this without wrapping widget with consumer:

final counter = Provider.of<CounterProvider>(context);

and using Text(counter.count.toString()) to get count.

i have tried both ways wrapping text widget with consumer and without wrapping. and i also added print statement print("build called"); inside build method to check if build method is getting called again and again. when i wrap the text widget with consumer and do this

Consumer<CounterProvider>( builder: (context, counter, child) => Text(counter.count.toString()))

then the the print statement is not calling again and again and i can also see increasing count

but if i use this method :

final counter = Provider.of<CounterProvider>(context);

Text(counter.count),

then i am getting build called in console so why so many peoples are using this method?

      .           . 

Solution

  • final count = Provider.of<CounterProvider>(context) is just a helpful way of getting the CounterProvider from the widget build tree. Think of context like a tree which stores all the data about widgets in our app. As you know that we wrap the root of our widget with CounterProvider() as in something like this:

    Widget build(BuildContext context) {
       return CounterProvider(child: MaterialApp(...));
    }
    

    So Provider.of(context) helps us gain access to the CounterProvider widget's state in its children using InheritedWidgets. The <CounterProvider> is a generic which specifies the type of provider to get from the widget tree. It is just a method to access the widget's state (CounterProvider widget). Also, it is used in the build method to render the current counter. I would recommend you read about InheritedWidgets to gain familiarity with them. Provider is just a wrapper around the inherited widgets. And to answer your question about why the build method is getting called sometimes and sometimes not, please post the complete code of the widget(Preferably a single main.dart file).

    Inherited Widgets

    Widgets, BuildContext, InheritedWidgets