Search code examples
flutterdartlocalizationinjectable

Flutter injectable package to inject AppLocalizations


I have a cubit that looks like this:

@injectable
class SomeCubit extends Cubit<SomeState> {
  SomeCubit({
    required this.logger,
    required this.someRepository,
    required this.flutterLocalNotificationsPlugin,
    required this.l10n, // AppLocalizations
    required this.anotherRepository,
  }) : super(SomeInitial());
}

Running the injectable generator throws an error about InvalidType because AppLocalizations isn't set up, but nothing I try allows AppLocalization to be injected.

I've tried doing it under the AppModule using @factoryParam, but it fails to generate code and fails out early. I've also tried applying the @factoryParam attribute in the SomeCubit constructor, but the same issue comes up.

Is anyone aware of how to do this and pass the current context in when attempting to get the SomeCubit dependency? I feel like there is a way to get this to work, but I'm missing something.

To summarize, I would like to use injectable with AppLocalizations.


Solution

  • So the issue is with injectable when it tries to generate the config.dart file.

    import 'package:flutter_gen/gen_l10n/app_localizations.dart'; is not an import that flutter will automatically add and it has to be pasted in manually all over the place. Since injectable couldn't automatically add this import it resulted in the generated file using InvalidType as a stand in which obviously broke the generated file.

    I came up with two options that worked.

    1. I removed the AppLocalizations parameter and instead passed in the BuildContext using @factoryParam. This worked, but I was worried about the context becoming outdated. Example:
    @injectable
    class SomeCubit extends Cubit<SomeState> {
      SomeCubit({
        required this.logger,
        required this.someRepository,
        required this.flutterLocalNotificationsPlugin,
        @factoryParam required this.buildContext, // BuildContext
        required this.anotherRepository,
      }) : super(SomeInitial());
    }
    
    1. I only used AppLocalizations in one method that was called when a button is pressed. I changed the method to take BuildContext context and then call AppLocalizations.of(context) from within that method. I went with this since the context would always be up to date and correct.