Flutter MobX Architecture

Ivan Terekhin
2 min readDec 10, 2019

--

Flutter with MobX

So, let’s talk about how we will receive our data in app. There are few rather popular libraries for this in Flutter: Dio (https://pub.dev/packages/dio) and Chopper (https://pub.dev/packages/chopper).

I choosed Chopper because I like the idea of code generation for such kind of things and because I saw great tutorial series about Flutter (https://resocoder.com/2019/07/14/chopper-retrofit-for-flutter-3-converters-built-value-integration/). If you will follow this tutorial you will have nice and clean WebService class which will be do “Get/Post/Delete” things for you and you will call the methods of this class in MobX stores. And you will use BuiltValue model classes.

But what about data persistence? There are several options in Flutter, including SQLite of course. But for mobile apps I prefer to use something simpler, because, you know, basically in mobile apps we don’t have really hard relations or so. So, Hive (https://pub.dev/packages/hive) is great to use it for data persistence. The only drawback is that we will have code duplication for Model classes (one for WebService models to parse and one for Hive).

And now, when we have all utilitary things installed let’s setup it in the main.dart file (where you are running you app). We will use the Provider for dependency injection (not exactly).

MultiProvider for Services

As you can see — we are just setting up Services (kind of utilitary things we using to get data) and Providing the Store to the Page Widget. You can just get it inside the build method of Page class, but I prefer this way. (explicit dependency)

So, what about Store class? Using MobX it will look like this:

Store example

This will allow you to implement some kind of cache-first approach (if you need it, it is very flexible, you can do anything you want there). Using actions you can add POST and DELETE handlers.

So, in you Page class, you can call something like widget.initUsers() in initState method of State class. And then, use Observer Widgets to show your data.

--

--

Ivan Terekhin
Ivan Terekhin

Written by Ivan Terekhin

Mobile developer (Android, iOS, Flutter), AI and GameDev enthusiast. https://www.indiehackers.com/jeuler

Responses (1)