1

I'm trying to come up with a scalable solution for factory registration in Dart/Flutter using injectable (or any other DI library).

Currently, I explicitly create a factory class (BarFactory) for each type (Bar), and call their create method (in Foo.doSomething) to create the instance (Bar):

import 'package:injectable/injectable.dart';

@singleton
class Foo {
  final BarFactory _barFactory;

  Foo(this._barFactory);

  void doSomething() {
    var bar = _barFactory.create();
    bar.blah();
  }
}

@injectable
class BarFactory {
  Bar create() => const Bar();
}

@injectable
class Bar {
  const Bar();

  void blah() {
    /* ... */
  }
}

The above dicatates writing a BarFactory for each Bar type. I can of course call getIt.registerFactory(() => Bar()) explicitly, but that's not much different from the above.

I tried to create a generic factory like this:

@injectable
class Factory<T> {
  final T Function() create;
  const Factory(this.create);
}

but that results in this error:

[SEVERE] injectable_generator:injectable_builder on lib/temp.dart:

Can not resolve function type
Try using an alias e.g typedef MyFunction = T Function();

which doesn't even make sense as T is a type parameter...

Any ideas on how to achieve this? I'm open to using a different DI library if it helps.

2
  • What do you think about code generation? I guess, since factories are pretty generic, this can be the case here. Commented Sep 29, 2024 at 12:57
  • @Sameri11 that's an eligible option if there's no simpler solution Commented Sep 30, 2024 at 10:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.