我有一肘,看起来像这样:
@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());
}
运行可注入生成器会引发有关 InvalidType 的错误,因为未设置 AppLocalizations,但我尝试的任何操作都不允许注入 AppLocalization。
我尝试在
AppModule
下使用@factoryParam
执行此操作,但它无法生成代码并提前失败。我也尝试过在 @factoryParam
构造函数中应用 SomeCubit
属性,但出现了同样的问题。
有人知道如何执行此操作并在尝试获取
SomeCubit
依赖项时传递当前上下文吗?我觉得有一种方法可以让它发挥作用,但我错过了一些东西。
总而言之,我想将注射剂与
AppLocalizations
一起使用。
您是否在应用程序的
MaterialApp
中定义了包的本地化委托?
像这样:
import 'package:your_package/l10n/app_localizations.dart' as your_package;
import 'package:flutter/material.dart';
import 'package:your_app/core/app_router.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router( // example from app using GoRouter..
title: "Your app",
localizationsDelegates: _localizationsDelegates, // set loca delegates here
supportedLocales: _supportedLocales, // set supported locales here
theme: ThemeData(
primarySwatch: Colors.blue,
),
routerConfig: appRouter,
);
}
Iterable<LocalizationsDelegate<dynamic>>? get _localizationsDelegates => [
AppLocalizations.localizationsDelegates, // your app's loca delegates
...your_package.AppLocalizations.localizationsDelegates, // your package's loca delegates
];
Iterable<Locale> get _supportedLocales => [
AppLocalizations.supportedLocales, // your_package's locales need to include the app ones
];
}