MobX- Api integration and state management

Pravin Palkonda
8 min readFeb 28, 2023

--

Hassle-free state management for the flutter application.

MobX is a state management library that makes it simple to connect the reactive data of the application from the UI. By using MobX we can easily consume reactive data in the UI. A large community supports MobX and is mostly used in other languages such as React, etc.

Go through the official documentation of MobX to understand it clearly.

Concepts used in MobX

  1. Observables → We can easily listen to the change in data just by making them observable. These data are known as reactive data. Observables represent the state of the application. These data can be easily consumed using the Observer widget.

We can easily create an observable for albumValue with an initial value.

We can also use the mobx_codegen package which allows us to use concepts of mobx with the annotations. Just use ‘@observable’ to make it observable. By using this we can keep track of anything change in the data.

Here we can easily track the albumList and isLoading values just by making them observables by ‘@observable’.

2. Computed Observable → Computed observable is the same as observable state and it is represented by using ‘@computed’ annotation. If the state of the observables changes then the value of the computed observable also changes as it is completely dependent upon the state of the observable.

Here the full name automatically changes as the first name and last name change.

3. Actions → Actions are the most useful property in mobx. It is used to change the state of observables. Actions are represented by ‘@actions’ annotations. Actions are any event that triggers a change in the value of the observable.

For example: In the counter example we can use the action property to easily increment the value. Such types of events in mobx are called actions.

4. Reactions → As we know every action has a reaction. Reactions are similar to the computed value, but the only difference is reactions trigger the side effect whenever the state of observable changes. After the action and the change in the observable, the action we take in return is called a reaction.

For example: Consider the counter-example, as an action we are increasing the value by 1. This value is displayed on the UI using an observer. Due to this action, the value increases and is also triggered in the UI which is known as a reaction.

In this article, we will fetch a list of data from the url, and add some items to this list of favorites. We will display these favorites on a new page.

Packages we need to install

  1. mobx → MobX is the library used for reactively managing the state of the application.
  2. flutter_mobx → Flutter mobx is a package that is a flutter integration of mobx.
  3. build_runner → It is a dart code generator package that is used to create a mixin in the mobx.
  4. mobx_codegen → It is a code generator for MobX that adds support for annotating the code with ‘@observable’, ‘@computed’, and ‘@actions’.
  5. Provider → We also need a provider package to maintain the state of the application globally.
  6. http → A package to handle http requests.

Go to pub.dev and install these dependencies in pubspec.yaml file.

Add mobx,flutter_mobx, and provider as dependencies, build_runner, and mobx_codegen as dev dependencies.

pubspec.yaml file

Project folder structure

We will create a basic folder structure. Each file will have a separate directory.

  • api -> Here we will create a file that will handle api requests.
  • constants → All the app-related constants go in this directory.
  • models → Here we will create a model file which will be helpful to parse the data into models.
  • pages → All the screen-related files go in this directory.
  • store → In this directory we will create mobx store files.
folder structure.

In the constants directory, create a dart file and name it constants.dart file.

In this file, we will create a constant that can be used throughout the application.

For example, We will create a constant for the album url through which we can fetch the list of album data.

constants.dart file

We can easily access the album url by using Constants.albumUrl.

In the model directory, create a file and name it album_model.dart.

In this file, we will create models for the response received by the album url. It will help us to parse json data to the album model easily during api calls.

We can easily create a model by using the quicktype.io tool. Just go to quick type and paste the response of the album url in the tool. It will generate a dart model.

Copy these dart codes generated by quick type and paste them on the album_model.dart.

album_model.dart file

In the api directory, create a dart file and name it album_api.dart.

In this file, we will handle the http request to fetch the list of album data from the album url. And we will parse the response data received by the api to the album model if the response is successful.

Now we need to create the most important file for using MobX properties. In the store directory create dart file and name it album_store.dart.

In this file, we will create a store for the album. Here we need to create an abstract class for the album store with Store.

The store is a mixin that is used for code generation which is a part of the mobx_codegen package. It will help us to use mobx properties with just annotations.

In this file, we create an empty list which is used for adding the list of data received from the api. We will make it observable by using ‘@observable’. We are making it observable to track the changes in the list so we can display it in the UI.

This file also includes an action that will trigger the api call to fetch the list of data and assign these data to the album list.

We also need to generate a mixin file using the build runner command. For this, we need to provide a proper file name.

For example, we have created album_store.dart file. In this file, we need to include the line part ‘album_store.g.dart’. After this, we need to use the build runner command in the terminal.

flutter pub run build_runner build

It will generate a new file with the name album_store.g.dart file. This should not be modified.

album_store.dart file

import 'package:mobx/mobx.dart';
import 'package:mobx_demo/api/album_api.dart';
import 'package:mobx_demo/model/album_model.dart';

part 'album_store.g.dart';

class AlbumStore = _AlbumStore with _$AlbumStore;

abstract class _AlbumStore with Store {
final AlbumApi albumApi = AlbumApi();

@observable
List<AlbumModel> albumList = [];

@observable
bool isLoading = false;

@action
getAlbums() async {
isLoading = true;
final list = await albumApi.getAlbums();
albumList = list;
isLoading = false;
}
}

Now we need to display the data which we have received from the api on the screen.

Create a dart file in the pages directory and name it home_screen.dart. Here we will use a stateless widget to display the list of data.

In this file, we create an instance of the AlbumStore in the build method and through this instance, we will call getAlbum() method which is in AlbumStore class. So it will make an api call to get the list of data using an http request.

To display the list we will wrap the Scaffold widget with the Observer widget. By using the observer widget we can easily consume the observable defined in the store files.

home_page.dart

class HomePage extends StatelessWidget {
const HomePage({super.key});

@override
Widget build(BuildContext context) {
final albumStore = AlbumStore();
albumStore.getAlbums();
return Observer(builder: (context) {
return Scaffold(
appBar: AppBar(
title: const Text("MobX Demo"),
),
body: albumStore.isLoading
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
shrinkWrap: true,
itemCount: albumStore.albumList.length,
itemBuilder: (context, index) => Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.amber,
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(10.0)),
child: Text(
"${albumStore.albumList[index].id} : ${albumStore.albumList[index].title} ",
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 16.0),
))));
});
}
}

Here we conclude the api integration using mobx. We learned how to create observable and actions. Consume an observable using the Observable widget.

Also, learn how to add items to the favorite list and use this list to display on a new screen. For this, we need a provider package as we need to display the list globally. We can manage the state using MobX on the same page but not globally as the store gets cleared when we move to a new page.

So we need to wrap MyApp with MultiProvider in the main.dart file. In this provider, we have to add the stores which we have to manage globally.

To understand it go through my code available on git.

Let me know in the comments if I need to correct anything. I will try to improve it.

Clap if you like the article. 👏

--

--