Working with MobX in Flutter

Mohit Joshi
Nov 27, 2019 · 6 min read

T his article focus mainly on Mobx and how it’s handled in Flutter. We will be covering setState(), MobX & Redux and their association with React by getting a general Knowabouts about their inner workings. By the End of this Blog read, you might be able to Differentiate b/w Redux & MobX as State Management Technique for your flutter Apps .Without any further delay, Let’s get started:-

Everything in Flutter constitute of widgets. Widgets are the basic building blocks that can be reused at a later time. They can be Classified into — stateless(No internal state exist) & stateful(Dynamic) widgets .

What is basically this “State” ?

State is information that can be read synchronously when the widget is built and might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes,using State.setState which is useful mainly when State is heiharchical and matches component structure.

Though, SetState has its own limitations :

  • Share More state across components — Internal state management become troublesome when you need to share more states across components.
  • Distant leaf components need access to states — Intermediary components doesn’t need to know becomes a problem as data gets shared to all pass through components.

To prevent This ,

We manage Application state externally to component by either of:

  • Bloc
  • Rx model
  • Provider
  • Scoped model
  • MobX
  • Redux model

Where individual leaf component can Access and Manipulate state.

MOBX: STATE MANAGEMENT TECHNIQUE

"MobX is just a state-management library that makes it really simple to connect the reactive data of your application with the UI” .

Here is a quick list of the MobX features that together make it Indispensable for Flutter:-

  • It is Simple, Scaleable and Unobtrusive state management library that has been very effective library for the JavaScript apps and this also port to the Dart language aiming to bring the same levels of productivity.
  • MobX is a Battle tested state management library Transparently Functional Reactive programming (TFRP). The design principle is very simple:Anything that can be derived from the Application state, should be derived Automatically : UI, data serialization, server communication, etc.
  • MobX is a state-management library that makes it simple to connect the reactive data of your application with the UI. This wiring is completely automatic and feels very natural. As the Application-developer, you focus purely on what reactive-data needs to be consumed in the UI without worrying about keeping the two in sync.
  • It’s not really magic but it does have some smarts around what is being consumed (Observables) and where (Reactions) and automatically tracks it for you. When the Observables change, all Reactions are re-run these Reactions can be anything from a simple console log, a network call to re-rendering the UI.

React and MobX together are a Prominent combination. React renders the application state by providing mechanisms to translate it into a tree of renderable components whereas MobX provides the mechanism to store and update the application state that React then further uses.

Both React and MobX provide optimal and unique solutions to common problems in Application development. React provides mechanisms to optimally render the UI by using a virtual DOM that reduces the number of costly DOM mutations. MobX provides mechanisms to optimally synchronize application state with React components by using a reactive virtual dependency state graph that is only updated when strictly needed and is never stale.

Why MobX is a solid State Management architecture for Flutter:-

  • Firstly, It uses comparatively less boilerplate code needed to implement State Management in MobX for Flutter when compared to other techniques at disposal and once all the actions are put into place, how the events will turn out and which properties to update are mainly not of concern.
  • Easy Interoperability: MobX works with plain JavaScript structures. Due to its unobtrusiveness, It works with most JavaScript libraries out of the box without Needing MobX specific library add-ons. For the same reason, you can use it with both server and client side, isomorphic and react-native applications.The result of this is that you often need to learn fewer new concepts when using MobX in comparison to other state management solutions.
  • Using Classes and Real References: With MobX you don’t need to normalize your data. This makes the library very suitable for very complex domain models.
  • Referential Integrity Is Guaranteed :Since data doesn’t need to be normalized and MobX automatically tracks the relations between state and derivations, you get referential integrity for free.
  • Rendering Through Many Levels :No problem, MobX will track them and re-render whenever one of the references changes. As a result, staleness bugs are eliminated. As a programmer, you might forget that changing some data might influence a seemingly unrelated component, but MobX won’t forget.
  • Simpler actions are easier to maintain: Modifying state when using MobX is very straightforward. You can simply write down your intentions. MobX will take care of the rest.

The above example makes use of the following properties of MobX that are vital. They are:-

State in MobX = Core-State + Derived-State

Observables are variables which represent the reactive-state of our application. They are also called ‘Event Generators’ because the state or value of an observable changes from time to time.
Actions are functions that decide how to mutate the Observables As a reason of this property, they are also called ‘Mutators’
Computed Observables are values which depend upon observables and get triggered when the observable they depend on, changes its state.
Observer Widgets are a special type of widget which acts as a listener to the observable properties being rendered on the screen, and simply changes the state and re-renders them whenever any change is observed.

Smaller Application

Rapid Prototyping

Less Boilerplate Code

Observe References

- Single domain class can Encapsulate all of the update logic,
- Reacting to state changes:Real time systems
- Learning Curve is easier,
- Maintainabilty and Scalibility are not a concern
- Automatically track update
Similarities:-
Open Source client side management libraries.
Describe UI as a function of state .
No relation to React.
Work Especially well with React
Redux:-
Action Required,
Single Store,
Plain-Object,
Immutable,
Normalized State
MobX:-Read and Write to State,
Multi- Store,
Observable Data,
Mutable,
Nested State

In this tutorial you will learn how to create a MobX version of the Review app-

Install Dependencies:

Add the following dependencies to your pubspec.yaml file.

dependencies:
mobx: ^0.3.8
flutter_mobx: ^0.3.3

Next add the following dev_dependencies:

dev_dependencies:
build_runner: ^1.3.1
mobx_codegen: ^0.3.9

In your project folder, run this command to fetch all the packages:

flutter packages get

At this point you possess all the necessary packages to continue further development:-

Implementation of MobX:

Using @observables and @actions annotations we have created reviews.dart

Observable & Actions usage pattern:

@observable
double averageStars = 0;

@action
Future<List<ReviewModel>> _getReviews() async {
final SharedPreferences _preferences =
await SharedPreferences.getInstance();
final List<String> reviewsStringList =
_preferences.getStringList('userReviews') ?? [];
final List<ReviewModel> retrievedReviews = [];

for (String reviewString in reviewsStringList) {
Map<String, dynamic> reviewMap = jsonDecode(reviewString);
ReviewModel review = ReviewModel.fromJson(reviewMap);
retrievedReviews.add(review);
}
return retrievedReviews;
}

Now we need to Run the below command inside our project folder. This generates Auto generated Code file

flutter packages pub run build_runner build

The changes need to be listened also in the UI view. This is done like where Row is wrapped alongwith Observer using builder:-

Observer(
builder: (_) {
return Row(
children: <Widget>[
InfoCard(
infoValue: _reviewsState.numberOfReviews.toString(),
),
],
);
},
),

This will generate a Ratings app with Comment and Rating functionality needed which will get displayed as list and added to average the overall rating on each new review :-

Conclusion:

MobX is framework Independent .

Though as per my suggestion , I would like to suggest you to try it out for your state management in flutter apps , Make Use of Actions if the changes are Event-based to avoid discomfort through handling.

Redux => MobX <=> MobX => Redux Easily doable .

Whatever you choose — It’s not an End game . Choose what makes you a Happy Developer!

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Mohit Joshi

Written by

Dart & Flutter Enthusiast.

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade