What is Provider?

A dependency injection system built with widgets for widgets. provider is 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.

home: ChangeNotifierProvider<NavigationProvider>(

builder: (_) => NavigationProvider(),

child: HomePage(),

),

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

Provider.of<provider-class>(context);

body: Consumer<NavigationProvider>(

builder: (context, navigationProvider, _) =>

navigationProvider.getNavigation),

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.