Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter to a Mobx Controller (Flutter)

I am an Android Developer and new to Flutter. I really like the way Mobx works, because it remembers me Android's ViewModel. By the way, when I create a ViewModel, I like to create it passing the repository as a parameter, so I can test it with different Data Sources (ie. local or cloud).

So, this is my class right now.

import 'package:mobx/mobx.dart';

part 'create_bill_controller.g.dart';

class CreateBillController = _CreateBillControllerBase
    with _$CreateBillController;

abstract class _CreateBillControllerBase with Store {
  final appBarTitle = 'Criar Conta';
  final criarConta = 'Criar conta';
  final nomeDaConta = 'Nome da conta';
  final seuNome = 'Seu nome';

  @action
  createBill(String billname, String userName) {
    // here, dataSource should be given in a constructor
    datasource.createBill(billName, userName);
  }
}

How can I pass a DataSource (repository) as a parameter to this class?

like image 975
Guilherme Oliveira Avatar asked Jun 08 '26 17:06

Guilherme Oliveira


1 Answers

What you need is to declare constructor for CreateBillController instead of _CreateBillControllerBase, because constructor is not inherited by child class in Dart. The simplest way is to assign the passed in datasource to the corresponding property in parent class in the constructor, as you can see in the below snippet. You can also implement a constructor for _CreateBillControllerBase as well and call super(datasource) in CreateBillController's constructor.

import 'package:mobx/mobx.dart';

part 'create_bill_controller.g.dart';

class CreateBillController extends _CreateBillControllerBase with _$CreateBillController {
  // HERE! Implement constructor for CreateBillController
  // Do this if you have a constructor for _CreateBillControllerBase
  //
  //   CreateBillController(DataSource datasource) : super(datasource)
  //
  CreateBillController(DataSource datasource) {
    super.datasource = datasource;
  }
}

abstract class _CreateBillControllerBase with Store {
  final appBarTitle = 'Criar Conta';
  final criarConta = 'Criar conta';
  final nomeDaConta = 'Nome da conta';
  final seuNome = 'Seu nome';
  // HERE! Declare datasource
  DataSource datasource;

  @action
  createBill(String billname, String userName) {
    datasource.createBill(billName, userName);
  }
}
like image 70
Lance Chen Avatar answered Jun 11 '26 10:06

Lance Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!