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
.
2
Answers
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. Sinceinjectable
couldn't automatically add this import it resulted in the generated file usingInvalidType
as a stand in which obviously broke the generated file.I came up with two options that worked.
AppLocalizations
parameter and instead passed in theBuildContext
using@factoryParam
. This worked, but I was worried about the context becoming outdated. Example:AppLocalizations
in one method that was called when a button is pressed. I changed the method to takeBuildContext context
and then callAppLocalizations.of(context)
from within that method. I went with this since the context would always be up to date and correct.Do you define your package’s localizations delegates in the app’s
MaterialApp
?like so: