Now The Interesting Part:

Now I need our attention…

Now Create a Counter class and encapsulate it. Create increment and decrement methods.

Counter Class

A very simple class and it has a mixin as it is followed by with keyword. The mixin is ChangeNotifier. Now, what is change notifier???

As you’ve probably must have guessed, all it does is add listening capability to our class in our case counter class.

inside the Increment and decrement method, there is a method call.

notifyListeners(); // it notifies the listener and updates the UI.

Now You have a tree of widgets. Now you want to put your class instance at least one level up where you want to use it. In our case, we want to use Counter class inside HomePage Widget. Inside the material app, we’ll wrap our homepage widget with ChangeNotifierProvider.

home: ChangeNotifierProvider<Counter>(

builder: (_) => Counter(0),

child: HomePage(),

)

Builder is the actual state object where we’ll instantiate our class. Don’t forget to put your class inside the < > as it is a generic widget and give the child.

Now We can access Counter object down the widget tree easily.

Accessing The Object:

Now inside the child tree widget, we can easily access our object using two ways. Either we can use Provider.of<Object>(context) or Consumer Widget. Here I have used the first one. But You can find the Snippet With Consumer from this link.

Final Code

Final Result

Is That All?

Offcourse not, In this example we have just barely touched the surface. There is a lot more in Provider. If you love working with rxdart and streams, there is also StreamProvider. I’ll be covering all this in my upcoming articles. so stay tuned.

Conclusion:

After all this, our app will be up and running. this was rather a simple example and full potential of this package was not shown. In my next article, I’ll try to deal with some real-world example(Maybe Firebase login) where we have multiple objects interacting with each other and state is rather complex.

Thank you for reading the article so far, and please let your feedback. Tell me if you want part 2 with a more complex example. You can find the above app from my GitHub. If you liked my article, Please do clap and follow for more. Thanks…