首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法使用flutter_localizations刷新子页中的文本,intl

无法使用flutter_localizations刷新子页中的文本,intl
EN

Stack Overflow用户
提问于 2022-07-04 12:50:13
回答 1查看 155关注 0票数 0

我正试图通过我的整个应用程序来改变本地化的单词。但是只有当我重新启动我的应用程序或者当我在lang上进行订阅时,它才会改变。有没有任何本地的方式来改变本地化的词,而没有任何订阅,并有相同的结果,我得到的时候,重新启动应用?

例如,在订阅项下,我指的是什么:

代码语言:javascript
运行
复制
//sets_bloc.dart
      void subscribeLocale(AppLanguagesCubit cubit) {
        cubit.stream.listen((event) {
          add(const OnSetCardsDownloading()); // refresh page
        });
      }
// home_view.dart
 MultiBlocProvider(
        providers: [
          BlocProvider<SetsBloc>(
            create: (_) => SetsBloc()
              ..subscribeLocale(BlocProvider.of<AppLanguagesCubit>(context))

          ),
          //..//
        ],
        child: SetsView(),
// main.dart
 /** */

Future<void> main() async {
  /** */

  await SentryFlutter.init(
    (options) {
      options.dsn =
      /** */
    },
    appRunner: () => runApp(
      MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
 /** */

  ExtendedSecureStorage get storage => DiManager.getIt<ExtendedSecureStorage>();

  @override
  void initState() {
 /** */
  }

  @override
  void dispose() {
 /** */
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        final FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus &&
            currentFocus.focusedChild != null) {
          FocusManager.instance.primaryFocus?.unfocus();
        }
      },
      child: MultiBlocProvider(
        providers: [
        //** */
        ],
        child: BlocBuilder<AppLanguagesCubit, AppLanguagesState>(
            builder: (_, AppLanguagesState state) {
          return OverlaySupport(
            child: MaterialApp(
              builder: (context, widget) {
                if (widget != null) {
                  return MediaQuery(
                    data: MediaQuery.of(context).copyWith(textScaleFactor: 1),
                    child: widget,
                  );
                }
                return widget ?? const SizedBox();
              },
              locale: state.status == ChangeLangStatus.success
                  ? state.selectedLanguage?.locale
                  : const Locale('en'),
              localizationsDelegates: const [
                S.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              supportedLocales: S.delegate.supportedLocales,
              debugShowCheckedModeBanner:
                  environmentConfig == EnvironmentConfig.dev ||
                      environmentConfig == EnvironmentConfig.qa,
              title: getAppName(),
              theme: ThemeData(
                primarySwatch: Colors.orange,
                unselectedWidgetColor:
                    LibraryColors.secondaryFont.withOpacity(0.5),
                canvasColor: Colors.white,
                primaryColorBrightness: Brightness.light,
              ),
              home: BlocConsumer<AuthBloc, AuthState>(
                listener: (context, state) {
                  if (state is ***) {
                    loadLanguage(context);
                  }
                },
                builder: (_, AuthState state) {
                  if (state is ** ) {
                    return _spinner();
                  }
                  if (state is AuthorizationCompleted) {
                    if (**) {
                      return MultiBlocProvider(
                        providers: 
                       /** */
                        child: CongratsView(),
                      );
                    }
                    if (Platform.isIOS) {
                      return const CupertinoScaffold(
                        body: HomeView(
                          initialTab: AppTab.home,
                        ),
                      );
                    }
                    return const HomeView(
                      initialTab: AppTab.home,
                    );
                  }
                  if (state is AuthorizationError) {
                    return WelcomeView();
                  }
                  return WelcomeView();
                },
              ),
            ),
          );
        }),
      ),
    );
  }

  Future<void> loadLanguage(BuildContext context) async {
    try {
      final String? code = await storage.read(key: 'languageCode');
      final Locale locale = getLocale(code, context);
      await S.load(locale);
      BlocProvider.of<AppLanguagesCubit>(context).init(locale);
      if (code == null) {
        await storage.write(
          key: 'languageCode',
          value: locale.languageCode,
        );
      }
      CurrentLocaleDi()
        ..setLocale(locale)
        ..inject();
    } catch (error) {
      await ErrorReporter.writeLogs(error);
    }
  }

  Locale getLocale(String? code, BuildContext context) {
    if (code == null) {
      return Localizations.localeOf(context);
    }
    return S.delegate.supportedLocales
            .firstWhereOrNull((locale) => locale.languageCode == code) ??
        S.delegate.supportedLocales.first;
  }

  Widget _spinner() {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        body: Center(
          child: Image.asset(
            LibraryAssets.appLogo,
            width: 121,
            height: 121,
          ),
        ),
      ),
    );
  }

  String getAppName() {
    const String appName = '***';
    switch (environmentConfig) {
      case EnvironmentConfig.dev:
        return '$appName dev';
      case EnvironmentConfig.qa:
        return '$appName qa';
      case EnvironmentConfig.prod:
        return appName;
    }
  }
}
//app_languages_cubit.dart
//** //

class AppLanguagesCubit extends Cubit<AppLanguagesState> {
  AppLanguagesCubit()
      : super(
          const AppLanguagesState.loading(),
        );

  ExtendedSecureStorage get _storage =>
      DiManager.getIt<ExtendedSecureStorage>();

  final List<AppLanguage> appLanguages = List<AppLanguage>.from(
    S.delegate.supportedLocales.map(
      (locale) => AppLanguage(
        locale: locale,
        code: locale.languageCode,
        lang: targetLangs[locale.languageCode] ?? '',
        langInNativeForm: locale.scriptCode ?? '',
      ),
    ),
  );
  void init(Locale locale) {
    final AppLanguage selectedLanguage = AppLanguage(
      code: locale.languageCode,
      lang: targetLangs[locale.languageCode] ?? '',
      locale: locale,
    );
    Intl.defaultLocale = selectedLanguage.locale.languageCode;
    emit(
      AppLanguagesState.success(
        status: ChangeLangStatus.success,
        selectedLanguage: selectedLanguage,
      ),
    );
  }

  Future<void> changeLanguage(AppLanguage selectedLanguage) async {
    try {
      emit(
        const AppLanguagesState.loading(),
      );
      Intl.defaultLocale = selectedLanguage.locale.languageCode;
      await S.load(selectedLanguage.locale);
      await _storage.write(
        key: 'languageCode',
        value: selectedLanguage.locale.languageCode,
      );
      CurrentLocaleDi()
        ..setLocale(selectedLanguage.locale)
        ..inject();


        emit(
            AppLanguagesState.success(
              status: ChangeLangStatus.success,
              selectedLanguage: selectedLanguage,
            ),
          );
        } catch (error) {
          await ErrorReporter.writeLogs(error);
          emit(
            const AppLanguagesState.failure(),
          );
        }
      }
    }
//ln10.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'intl/messages_all.dart';

// **************************************************************************
// Generator: Flutter Intl IDE plugin
// Made by Localizely
// **************************************************************************

// ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars
// ignore_for_file: join_return_with_assignment, prefer_final_in_for_each
// ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes

class S {
  S();

  static S? _current;

  static S get current {
    assert(_current != null,
        'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.');
    return _current!;
  }

  static const AppLocalizationDelegate delegate = AppLocalizationDelegate();

  static Future<S> load(Locale locale) {
    final name = (locale.countryCode?.isEmpty ?? false)
        ? locale.languageCode
        : locale.toString();
    final localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((_) {
      Intl.defaultLocale = localeName;
      final instance = S();
      S._current = instance;

      return instance;
    });
  }

  static S of(BuildContext context) {
    final instance = S.maybeOf(context);
    assert(instance != null,
        'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?');
    return instance!;
  }

  static S? maybeOf(BuildContext context) {
    return Localizations.of<S>(context, S);
  }

  /// `**`
  String get sliderText1 {
    return Intl.message(
      'some text'
      name: 'sliderText1',
      desc: '',
      args: [],
    );
  }
//** */
}

class AppLocalizationDelegate extends LocalizationsDelegate<S> {
  const AppLocalizationDelegate();

  List<Locale> get supportedLocales {
    return const <Locale>[
      Locale.fromSubtags(languageCode: 'en'),
      Locale.fromSubtags(languageCode: 'de'),
      Locale.fromSubtags(languageCode: 'es'),
      Locale.fromSubtags(languageCode: 'fr'),
      Locale.fromSubtags(languageCode: 'ja'),
      Locale.fromSubtags(languageCode: 'pl'),
      Locale.fromSubtags(languageCode: 'pt'),
      Locale.fromSubtags(languageCode: 'ru'),
      Locale.fromSubtags(languageCode: 'tr'),
      Locale.fromSubtags(languageCode: 'uk'),
      Locale.fromSubtags(languageCode: 'zh'),
    ];
  }

  @override
  bool isSupported(Locale locale) => _isSupported(locale);
  @override
  Future<S> load(Locale locale) => S.load(locale);
  @override
  bool shouldReload(AppLocalizationDelegate old) => false;

  bool _isSupported(Locale locale) {
    for (var supportedLocale in supportedLocales) {
      if (supportedLocale.languageCode == locale.languageCode) {
        return true;
      }
    }
    return false;
  }
}
EN

回答 1

Stack Overflow用户

发布于 2022-09-10 06:42:57

您可以更改整个应用程序,无需任何订阅和设置状态。您必须使用await WidgetsBinding.instance.performReassemble();,这是用更新的value.This触发整个应用程序的函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72857069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档