Is it ok to export a Store as a singleton in Flutter Mobx?

Viewed 952

I'm working with Flutter-Mobx as state management system in my Flutter project. I'm also using mobx_codegen as dev dependency in order to help me generate the Stores.

I usually see people instanciating their store directly in the Widget when it's something simple, or using some sort of dependency injection.

I'm wondering if it's ok to provide the Store as a singleton in the same file in which it was created. I've made some tests and it's working, but under the perspective of internals, side effects, memory management and good practices, is there something wrong?

here is my Store file, controller.dart (remember _$_Controller is auto generated with mobx_codegen):

import 'package:mobx/mobx.dart';
part 'controller.g.dart';

class _Controller = _ControllerBase with _$_Controller;

abstract class _ControllerBase with Store {
  @observable
  int a = 0;

  @action
  increment(){
    a++;
  }
}

//Here is my singleton export
_Controller _singleton = _Controller();
_Controller get singletonControler => _singleton;

In my exemple Widget it would look like this:

import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:elec/src/controller.dart';



// "singletonControler" comes directly from the import
// somewhere in the widget tree...
Observer(builder: (_) => Text(singletonControler.a.toString()))

// in other location of the tree...
FloatingActionButton(
    onPressed: singletonControler.increment)
0 Answers
Related