Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Managing the state of a Widget using Provider | Flutter

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

/media/72482944219ad3fe84e7b3bb2943a8ab

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

/media/834f4d14010bf649ffd6cc2c12994846

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.

/media/e7895e2bdaf6f0cb99ca251d6a54adc4

Now its time to run the app.


We have also linked a repo.

ashishaeologic/Flutter-ProviderExample
Contribute to ashishaeologic/Flutter-ProviderExample development by creating an account on GitHub.github.com

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.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.