skip to Main Content

Can anyone help me with using dependency injection on singleton?
here is my code:

class SpaceController extends ChangeNotifier {
  final SpacesPersistence _persistence;

  static final SpaceController _instance = SpaceController._internal(persistence: null);
  factory SpaceController({required SpacesPersistence persistence}) {
    return _instance;
  }

  SpaceController._internal({required SpacesPersistence persistence}) : _persistence = persistence;
}



abstract class SpacesPersistence {
  Future<List<Entry>> getPath();

  Future<List<Entry>> getEntries(Entry? parent, [String? keyword]);

  Future<List<Connection>> getConnections([List<Entry>? entries]);

  Future<void> add(Entry entry);

  Future<void> remove(Entry entry);

  Future<void> update(Entry entry);

  Future<void> setPath(List<Entry> path);
}

This problem is that I want to inject the persistence variable, but _internal requires the argument and _persistence is not ready yet.

2

Answers


  1. Try with passing new instance in _instance. Here SpacesPersistenceImpl is a class which implements SpaceController

    class SpaceController extends ChangeNotifier {
      final SpacesPersistence _persistence;
    
      static final SpaceController _instance = SpaceController._internal(persistence: SpacesPersistenceImpl());
      factory SpaceController() {
        return _instance;
      }
    
      SpaceController._internal({required SpacesPersistence persistence}) : _persistence = persistence;
    }
    
    Login or Signup to reply.
  2. I simply grab a RiverPod provider, which gives me lazy initialization, discoverability as a singleton, and dependency injection via overrides for mocking during testing. Details at http://riverpod.dev/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search