In this article, I am going to explain Flutter Provider in a short and easily understandable way. Two days back when I tried to understand the Logic behind State management using Flutter Provider I, checked many explanatory videos and articles and gathered all the concepts and going to put them all here.
I am going to explain the provider by making a Shopping Cart in Flutter. First of all, we need to define our Item class this one is basic so not focusing much on this. You can check one example here and add as many parameters as per need.
Now we are going to implement the UI of The App i.e the home page which will show the cart list item and an additional add item page from which we will add the items. Here are two examples of two pages.
Now the main part starts. For Implementing Provider we basically need three things. 1)CartItemProvider Class (for maintaining all logic), 2)ChangeNotifierProvider(to wrap the widget preferably Material Widget), And 3)Consumer ( To consume ). Don’t forget to add the provider package to your pubspec.yaml file.
Note the two things here first the extended class ChangeNotifier which will Notify all the widgets which are depending on this class and the notifyListenerts() which will notify all the time whenever any change is detected.
Here is the code for the previous two screens Home and AddItem Screen after adding Consumer on them.
The main.dart file look like this after wrapping with ChangeNotifierProvider
I have also implemented a theme-changing simple logic to show we can Implement multiple Providers at the same time. The updated main.dart page will look likes this.
Here we can see MultiProvider wrapping the Material Widget. Below our final product will look like.
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…
Here you can check the source code for this implementation. Don’t forget to add a 👏 clap. Thanks for reading.
You can check my other works here.