如何在BLOC中使用Flutter本地化来翻译消息?

oknwwptz  于 2023-02-20  发布在  Flutter
关注(0)|答案(1)|浏览(110)

我正在Flutter中开发一个应用程序。我使用flutter_localizations包进行本地化,使用intl包进行国际化。为此,我使用了Widget中的Context,但问题是当我想在块或存储库或除UI层之外的其他层中使用国际化时。
除了UI层之外,在其他层中进行国际化的最佳实践是什么?UI层中我们无法访问Context。
我试过使用Singleton,但我不知道这是否是正确的方法。

deikduxw

deikduxw1#

您必须传递应用本地化。例如,在Cubits中,您可以执行以下操作:
main.dart

runApp(
 MaterialApp(
  localizationsDelegates: [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    const Locale('en', ''),
    const Locale('pl', ''),
  ],
  title: 'MySuperApp',
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.orange,
    accentColor: Colors.deepOrangeAccent,
    visualDensity: VisualDensity.adaptivePlatformDensity,
  ),
  initialRoute: '/',
  routes: {
    UserAuthScreen.routeName: (context) => const UserAuthScreen(),
    HomePage.routeName: (context) => HomePage(),
    ...
  }, 
  builder: (context, child) {
    final appLocalizations = AppLocalizations.of(context); //IMPORTANT
    return MultiBlocProvider(
      providers: [
        BlocProvider<ConstantsCubit>(
          lazy: true,
          create: (context) => ConstantsCubit(
            constantsRepository: ConstantsRepository(),
          ),
        ),
        BlocProvider<UserAuthCubit>(
          lazy: true,
          create: (context) => UserAuthCubit(
            localizations: appLocalizations, //THIS IS WHERE THE MAGIC HAPPENS
            repository: UserAuthRepository(),
          ),
        ),
        BlocProvider<DoerInfoCubit>(
            lazy: true,
            create: (context) => DoerInfoCubit(
                  doerInfoRepository: DoerInfoRepository(),
                  userAuthCubit: BlocProvider.of<UserAuthCubit>(context),
                )),
        ...
      ],
      child: child,
    );
  },
  home:
      BlocBuilder<UserAuthCubit, UserAuthState>(builder: (context, state) {
    if (state is UserAuthLogged) {
      return HomePage();
    } else {
      return const UserAuthScreen();
    }
  }),
),
);

在你的块或肘中:

class UserAuthCubit extends Cubit<UserAuthState> {
 final UserAuthRepository repository;
 final AppLocalizations localizations; 

 UserAuthCubit({
   @required this.repository,
   @required this.localizations,
 }) : super(const UserAuthInitial()) {
   getUserAuthState();
 }

相关问题