In this article, I'll be showing you how you can use Flutter Provider package in the BottomNavigationBar.

What is Provider?

Provider is a new state management approach recommended by the Flutter team.

Note

setState also works fine for many case , you should not use it every where .

But in case you have a messy code like you have a FutureBuilder in the build then setState will definately cause problem.

Let's see how we can use it in BottomNavigationBar.

Step 1: Add the dependency in your pubspec.yaml.

provider : <latest-version>

Step 2: Create a provider class

class BottomNavigationBarProvider with ChangeNotifier {

int _currentIndex = 0;



get currentIndex => _currentIndex;



set currentIndex(int index) {

_currentIndex = index;

notifyListeners();

}

}

In this provider, I am storing the current value of the BottomNavigationBar and when the current value is set into to provider, the BottomNavigationBar will be notified with the current value and update the tab.

Step 3: Wrap parent Widget with ChangeNotifierProvider

home: ChangeNotifierProvider<BottomNavigationBarProvider>(

child: BottomNavigationBarExample(),

builder: (BuildContext context) => BottomNavigationBarProvider(),

),

I have wrapped my widget with ChangeNotifierProvider so my widget will be notified when the value changes.

Step 4: Create tabs for BottomNavigationBar

I have three widgets tabs which I’ll attach with my bottom navigation bar.

Step 4: Create BottomNavigationBar with provider

So I have created a list for the screens and change the screens with an index which is provided by the provider and the tab changes the provider updates the index.

Here is the code for the above example :

Persistent BottomNavigationBar