Flutter MobX Example Architecture
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:
Here is our StorageService class:
Here is our implementation of StorageService:
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.
Now let’s define MobX store that will manage data retrieve:
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/.