Working with MobX in Flutter
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 & MobX
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 basic structure of a MobX based application:
The above example makes use of the following properties of MobX that are vital. They are:-
State in MobX = Core-State + Derived-State
Observables
https://gist.github.com/JOSHIMOH/760b7842a26a12930d8b7e76edffe4e9#file-observable-in-mobx
Actions
are functions that decide how to mutate the Observables As a reason of this property, they are also called‘Mutators’
https://gist.github.com/JOSHIMOH/770593b433d0247351a59ad116e13b41#file-actions
Computed Observables are values which depend upon observables and get triggered when the observable they depend on, changes its state.
https://gist.github.com/JOSHIMOH/df93ad0afefd974fa09a47d5f78e9a3b#file-computed-observable
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.
MobX
- 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
MobX Vs Redux: Comparing the opposing Paradigms
Similarities:-
Open Source client side management libraries.
Describe UI as a function of state .
No relation to React.
Work Especially well with React
https://gist.github.com/JOSHIMOH/1ef1df285139d0ce1a2fc1c6a2bc1037#file-plain-in-redux
https://gist.github.com/JOSHIMOH/a4fa2962b292be380b280d685086f7d5#file-redux
Redux:-
Action Required,
Single Store,
Plain-Object,
Immutable,
Normalized State
https://gist.github.com/JOSHIMOH/c806a9519b396fed7a5cc4378996af50#file-observable-in-mobx
MobX:-
Read and Write to State,
Multi- Store,
Observable Data,
Mutable,
Nested State
Making a simple Review App using MobX for Flutter
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: ^latest version
flutter_mobx: ^latest version
Next add the following dev_dependencies:
dev_dependencies:
build_runner: ^latest version
mobx_codegen: ^latest version
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
https://gist.github.com/JOSHIMOH/d6749dee5c27c6c4f430863665469e1f#file-review-g-dart
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!
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.