Before discussing the State Management Mechanism in Flutter, let’s get a brief introduction to the State in Flutter. In Flutter, state related to the widget information when the widget is created. The state might be changed through the life cycle of the widget.
There is a variety of State Management Mechanism in Flutter, let’s go through a few of them
You can also go through our Flutter app development services page.
1. setState
This method is one of the most used methods for state management in a flutter. This method internally calls the build method which has a return type of Widget to render the view. Every time we invoke this method it directly calls the build method and UI will update accordingly.
1 2 3 4 5 6 7 8 |
void _incrementCounter() { setState(() { if (_counter == 5) { levelReached = true; } _counter++; }); } |
In the above piece of code, we have set the flag “levelReached” to true for handling the click event on the button. If it is true then it will call “blankMethod” otherwise it will call the “_incrementCounter” method and update the counter value.
1 2 3 4 5 |
floatingActionButton: FloatingActionButton( onPressed: levelReached ? blankMethod : _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ) |
2. Provider
It is the most basic of the provider widget in Flutter. We can use it to pass data (normally data models) b/w the widget tree. But it doesn’t help you to update the widget tree when data changes. For updating the widget, we can use “ChangeNotifierProvider”. for example:
1 2 3 4 5 6 7 8 9 10 11 |
class Increment extends ChangeNotifier{ var intVar = 0; int get getCounter { return intVar; } void incrementCounter() { intVar += 1; notifyListeners(); } } |
Created a class that extends the change notifier class. In this class, we have define a getter method and incremental method for getting and incrementing the values. Then we use this class in the main class where we want to change the values:
1 2 3 4 |
void _incrementCounter() { Provider.of<Increment>(context, listen: false).incrementCounter(); } |
There are many methods in flutter for state management, but here we have explained a few of them.
1.InheritedWidget & InheritedModel
2. Redux
3. Fish-Redux
4.BLoc
5. GetX
6. RiverPod
7. Binder