What is Provider?
A dependency injection system built with widgets for widgets.
provideris mostly syntax sugar for
InheritedWidget, to make common use-cases straightforward.
Let’s build a very simple navigation app with the Provider package.
We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen just like Navigation menu fragment transaction.
This is just like a Fragment Transaction in an Android app.
Step 1: Add the dependency in your pubspec.yaml.
provider : <latest-version>
Step 2: Create a Provider class
In this provider class, we have implemented our logic which is to update the current navigation value.
updateNavigation will update the current value of the navigation and notify the listener.
To notify, you need to add the ChangeNotifierProvider to the root of the Widget tree.
builder: (_) => NavigationProvider(),
Step 2.1: Update the UI
Unlike Bloc, you do not need to use the StreamBuilder to update the UI.
navigation.getNavigation will return the body as declare in the provider class above.
Step 2.2: Update the UI with Consumer
You can also use Consumer to get the value and update the UI then you do not need to use
builder: (context, navigationProvider, _) =>
Step 3: Add the drawer
Whenever we tap on any drawer item, first it will close the drawer menu using
Navigator.of(context).pop()then it updates the provider which changes the navigation value and the provider will update the UI.
Now its time to run the app.
We have also linked a repo.
Contribute to ashishaeologic/Flutter-ProviderExample development by creating an account on GitHub.
Thanks for reading this article ❤
We got something wrong? Let me know in the comments. We would love to improve.
Clap 👏 If this article helps you.
Connect with me on LinkedIn.
Check my GitHub repositories.
Follow me on Twitter.