Where most of Flutter state managements came from?

Thiago Evoá
3 min readFeb 22, 2022

--

Hello dev, have you ever thought how most Flutter state management works? Well, if I tell you that they use the SDK native approach? Let’s check this out to see what I’m talking about.

If you think just a little, maybe the first thing that may come in mind is, how things can be propagated down in the widget tree? For example in the Bloc package, if you do not provide a bloc class up in the widget tree and try to use it, you will get an exception saying that the code tried to find a reference that does not exist.

And here comes the InheritedWidget class, which basically is a type of widget that propagates information down the widget tree. This is the short explanation provided by the documentation. Making things clear let me show a very simple example to help you understand.

The first thing to do is create a class that extends the InheritedWidget and provide in the constructor a key and a child in order to pass it to the super class.

In this example I also added to the constructor a value property which is going to hold the information, and a function property to trigger an action and change the value.

Another thing that is not mandatory in the class, but will be needed, is add a static method for returning the logic in case there is not it’s own widget in the widget tree.

counter_state.dart

And as you can probably see, I’m using the counter app as usual to show case the example.

counter_widget.dart

Moving forward, let’s create the widget responsible for wrapping the InheritedWidget class that you created and make things usable. Note that the setState will make the widget rebuild after a change.

my_home_page.dart

Now to use all this, you have to instantiate the CounterState class using the static method, but if you try to run the code like this, you will see an exception saying that cant find this class on the widget tree.

To solve this, put the first widget of the tree inside the CounterWidget.

main.dart

The result will be the counter app functioning as expected.

app

It’s possible that you are wondering why this article, but the thing here is, make you curious to read and search how things work under the hoodie, because sometimes you face a problem and don’t know what’s going on just because you are using packages to help you out, so listen to this tip…Go ahead and read the documentation.

--

--