Managing the state of a Widget using Provider | Flutter

Ashish Rawat
Apr 19 · 3 min read

What is Provider?

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.


We have also linked a repo.

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.


FlutterDevs has been working on Flutter from quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Ashish Rawat

Written by

Android and Flutter Developer

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.