HOW CAN WE DO STATE MANAGEMENT IN FLUTTER?

Muhammad Ibrahim
2 min readApr 1, 2021

The very first question that arises here is what is state management? A state is a collection of variables at a certain amount of time. Our computer is actually a state machine which shows the users the combination of different states likewise in a reactive framework like flutter State management refers to the management of the state of one or more user interface controls.

You can think of the UI as the return value of the function, that function gets called with one argument which is your state, so in literal meaning state is a data that changes with lifecycle of the app. A lot of your data can be self-contained within one widget.

Firstly, let’s begin with the fundamental building blocks in flutter, starting with the stateful widget.

STATEFUL WIDGET

When you run flutter create from the command line it gives you some starter code, that increments a counter with a widget. To rebuild this counter, we’ll apply different state management strategies in this article. To create the stateful widget we need two classes, one is stateful widget itself and that returns our second class which so an extension of our state class and this is where all the heavy lifting happens, first we define the property called counter which is an actual data state and the other one we define a method called the increment counter and it calls a called “SET STATE” which will tell this widget to re-render when this value changes. After that we implement build function which defines actual widget that will be rebuilt every time set state is called. Stateful widgets are prominent for managing simple local state but there is some couple of things which are bit confusing while using it.

STATEFUL BUILDER

Stateful widget plays a significant in simplifying the stateful widget code. Stateful widget takes a builder function , that function gives us the access to the builder context and also the function called set state to rebuild all the wingets inside this function.

INHERITED WIDGET

It is the widget that allows us to pass context to any of its decendants. In inherited widget, the inherited counter built into flutter and it will take child as an argument from its constructor from where I have override a method called update should notify and this will run when this inherited widget will rebuilt and will notify any descendent whether or not. Here we have implemented the static method. Now here the inherited widget is immutable and I have define our counter data as map. And then we need to define an increment method which allows us to increment the counter value and then we’ll add a getter to get the current value.

--

--

Muhammad Ibrahim

I'm a flutter developer, having active working experience of more than 2 years developing mobile apps.