Is there a way to pass factory params?
Asked Answered
S

2

7

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>(),
              ));
Sucrase answered 8/12, 2020 at 5:46 Comment(0)
F
1

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

Frodine answered 22/12, 2022 at 20:58 Comment(0)
M
0

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?

Mortar answered 8/12, 2020 at 7:31 Comment(3)
How to use HotelsBloc, if it creates SettingBloc without event parameter? Event parameter is mandatory in SettingsBloc, and cannot be omitted. And there is no documented way to pass that parameter from HotelsBloc.Sucrase
I clarified what I expect in P.S. section of my question.Sucrase
@AlexanderFarkas could you find solution for this, I have the same problemSebastiansebastiano

© 2022 - 2024 — McMap. All rights reserved.