Search code examples
fluttermobx

Flutter mobx mobx_codegen generates null safety code for computed getters


Using mobx and mobx_codegen for Flutter.

My code is NOT null safe (sdk: ">=2.7.0 <3.0.0").

When mobx_codegen generates code for @computed getters, it uses null safety, which won't compile...

Sample class counter (look at @computed):

import 'package:mobx/mobx.dart';

// Include generated file
part 'counter.g.dart';

// This is the class used by rest of your codebase
class Counter = _Counter with _$Counter;

// The store-class
abstract class _Counter with Store {
  @observable
  int value = 0;

  @computed
  int get test => 0;

  @action
  void increment() {
    value++;
  }
}

Relevant generated code (counter.g.dart):

Computed<int>? _$testComputed;

Shows this error: This requires the 'non-nullable' language feature to be enabled. Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get'.

I'm new to mobx, am I doing something wrong?


Solution

  • Since you're using a version of MobX that has null-safety, you can either:

    • migrate your code to null-safety (recommended).
    • downgrade your mobx, mobx_codegen and build_runner packages to a version that doesn't have null-safety.

    To migrate your code, you can follow this Migration Guide.

    If you opt to downgrade, be aware that you might run into version conflicts and there's a chance you have to downgrade your Flutter SDK too.