Reflecting app state on screen easily in Flutter

Thiago Evoá
3 min readFeb 10, 2022

--

Hello dev, here in this article I’ll show a simple way to create states in your app and use then to reflect in the screen, in order to present to the user that the app is doing something after a request. So let’s go straight to the code.

As usual the first thing you need to do is, add the needed dependencies into the pubspec.yaml. Here are the ones that I’m using and if you don’t know any of these, try to go to the pub.dev in order to read the documentation, because it’s not the focus explain it here each one of the packages.

pubspec.yaml

Now let’s define the class which will represent the json coming from the request that we are going to create later. In this step I encourage you to read about code generation in Flutter in case you have never read about it.

post.dart

Now let’s create the abstract class and also the implementation witch will make the http call, to retrieve a list of fake posts from a mock api.

interface
implementation

So, now it’s time to explain a little more about how we are going to implement the different states in the app, and for that we can implement a pattern based on the Segmented State Pattern.

Basically we are going to have an abstract class and then have some classes that extends it for representing the different states.

states

Note that for some states we can hold a value, so it’s going to be possible to get this value when you have the state available.

Now we can create a simple ValueNotifier to help us to control the app’s state management.

ValueNotifier

Note that we can change the state based in different situations we have, while calling the backend.

Now is the time to create the screen elements, and as dependency injection I’m using the provider package to inject the needed dependencies.

provider

And last, the screen it self. Here the only thing we need to reflect the states is make a conditional structure in order to change the widgets according to the states while the data is being processed.

home_page

As the result we are going to have this.

app

The key here is that you don’t need to install a external package to help your with the state management in your app, depend on your needs you can simply use the one provided by the the technology you are using and create mecanisms to improve the code.

--

--