Is there a way to pass factory params?

1.5k Views Asked by At

I have something like that:

@injectable
class SettingsBloc {
  final Event event;

  SettingsBloc(@factoryParam this.event);
}

When I call it from my code, I pass factory param like: getIt<SettingsBloc>(param1: Event())

But when SettingsBloc is something's dependency, call is autogenerated and looks like this: get<SettingsBloc>()

Generated code:

gh.factoryParam<SettingsBloc, Event, dynamic>(
      (event, _) => SettingsBloc(event));

gh.factoryParam<HotelsBloc, Event, dynamic>(
      (event, _) => HotelsBloc(
            event,
            get<SettingsBloc>(),
          ));

So, factory param is not passed, and everything crashes at runtime. How can I fix this?

P.S. Long story short: there should be a way to generate this code:

gh.factoryParam<HotelsBloc, Event, dynamic>(
          (event, _) => HotelsBloc(
                event,
                get<SettingsBloc>(param1: event),
              ));

Instead of this:

gh.factoryParam<HotelsBloc, Event, dynamic>(
          (event, _) => HotelsBloc(
                event,
                get<SettingsBloc>(),
              ));
2

There are 2 best solutions below

3
On

The code works as expected

 print(getIt<SettingsBloc>().event);
  // prints null
  print(getIt<SettingsBloc>(param1: Event()).event);
  // prints Instance of 'Event'

Are you sure you're initializing getIt before using it?

0
On

According to my understanding of passing parameters to inner dependencies, you should create a Module for the classes that depend on SettingsBloc.

@module
abstract class HotelsBlocModule {
  HotelsBloc createHotelsBloc(
    @factoryParam Event event,
  ) => HotelsBloc (
         get<SettingsBloc>(
           param1: event,
         ),
       );
}

Also, you will have to remove @injectable from HotelsBloc, since the Module now handles HotelsBloc creation.

class HotelsBloc {
  final SettingsBloc _settingsBloc;

  const HotelsBloc(
    this._settingsBloc,
  );

  ...
}

Documentation: Module class | lib documentation