Dart dependency injection - why can't I pass an instance reference to class members?

329

Solution 1

You can't use this in initializers, but you could use it in a constructor, if you drop the final qualifier.

class Root {
  StoreA storeA;

  Root() {
    storeA = StoreA(this);
  }
}

Solution 2

Richard Heap's answer is currently the correct answer, but in a future release of Dart which includes a non-nullable type system, you'll be able to write the following:

class StoreA {
  final Root _root;

  StoreA(this._root);
}

class root {
  late final StoreA = StoreA(this);
}

You can see the specification for non-nullable by default (NNBD) and related features like late fields at the Dart language repository.

Share:
329
Marc F
Author by

Marc F

Updated on December 17, 2022

Comments

  • Marc F
    Marc F over 1 year

    I'm currently writing an app using Flutter and began refactoring my state management using MobX. Since I have several stores that will communicate with each other, I attempted to "connect" these stores as suggested in the MobX best practices: https://mobx.js.org/best/store.html#combining-multiple-stores.

    Create a "root" store which holds the other stores as members, each containing a reference to the root store.

    For some reason I am unable to do this seemingly simple thing. I have searched a lot but couldn't find an answer.

    This is basically what I want to do:

    class StoreA {
      final Root _root;
    
      StoreA(this._root);
    }
    
    class root {
      final StoreA = StoreA(this);
    }
    

    The dart analyzer complains:

    Invalid reference to 'this' expression

    • Rémi Rousselet
      Rémi Rousselet over 4 years
      this is simply not allowed inside initializers