Flutter MobX Example Architecture

Ivan Terekhin
2 min readApr 4, 2020

--

Fluter is great

So, you like Flutter (and Dart) and MobX? You can easily implement this architecture in your Flutter application. I’m using Chopper for Networking, Hive for Cache and Data storage, MobX as State management approach, Provider for Dependency Injection (more like service locator things).

Let’s start with our Network layer using Chopper (https://pub.dev/packages/chopper). There is, actually, a great tutorial about Chopper, which is larger than this article — https://resocoder.com/2019/06/19/chopper-retrofit-for-flutter-basics/. You should read this series (I read and use code).

Here is our WebService class:

WebService example

Here is our StorageService class:

StorageService interface

Here is our implementation of StorageService:

StorageService implementation

Also, we have defined models like this (you can see a code duplication in this approach — I don’t feel it is bad, we can extend our Hive models with some additional fields.

User model (used in WebService auto parsing of JSON)
User model (used in StorageService and in Stores)

Now let’s define MobX store that will manage data retrieve:

MobX User Store.

Let’s use this store in our simple UI. To provide our store we will use the Provider package (https://pub.dev/packages/provider).

So, the UI will be looking something like this

Observer(
builder: (_) => widget.userProfileStore.user.value != null
? _buildUserInfo(widget.userProfileStore.user.value)
: Center(child: PlatformCircularProgressIndicator()));

Of course, this is like a “dumb” example of how things can be organized with those libs, but I like it. You can improve your code by using “states” more, for example, you can define “Loading state”, “Error state”, “Data state” and work with this approach inside your widgets. You can find such examples in the amazing Reso articles (coolest guy about Flutter) — https://resocoder.com/2019/12/26/flutter-mobx-tutorial-transparent-reactive-state-management/.

--

--

Ivan Terekhin
Ivan Terekhin

Written by Ivan Terekhin

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

No responses yet