在Dart中显示本地化标签时出现问题

时间:2019-08-05 06:19:03

标签: flutter

我无法在我的应用中设置本地化。

我正在尝试在我的应用程序中添加语言设置和相关的本地化。我可以设置语言选项。我正在使用'intl'插件进行国际化。我的代码几乎在所有UI .dart文件中都如下所示。

AppTranslations.of(context).accountNumber +
                    " ${accountDetails.accountNumber}",

将吸气剂设置为:

String get accountNumber => _text("account_number");

String _text(String key) {
    return _localisedValues[key] ?? _defaultLocaleValues[key];
  }

我还放置了包含3种不同语言的本地化标签的json文件。但是,似乎存在定位插件的实例化问题。该代码行不通。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

AppTranslations.of(context)是访问本地化标签的标准方法。您对实例化是正确的。如果程序没有到达他们的getter行,则意味着代码的初始部分存在问题。可能在main.dart中。

检查您要在哪里初始化LocalStorageProvider()。如果未初始化,那就是问题。假设您正在使用MaterialApp,请尝试以下建议: 用LocalStorageProvider()包装MaterialApp。我的意思是,在主窗口小部件构建中,返回LocalStorageProvider()并将您现有的MaterialApp()代码作为子代传递给它。下面的示例(由于我只是从我的一个应用程序中复制了代码,请忽略主题等):

@override
  Widget build(BuildContext context) {
    LocalStorage localStorage = LocalStorage();
    return LocalStorageProvider(
      localStorage: localStorage,
      child: LocaleProvider(
        localStorage: localStorage,
        localeWrapper: LocaleWrapper(),
        child: Builder(
          builder: (context) {
            return AnimatedBuilder(
              animation: LocaleProvider.of(context).localeWrapper,
              builder: (context, _) {
                return MaterialApp(
                  onGenerateTitle: (context) =>
                      AppTranslations.of(context).appName,
                  locale: LocaleProvider.of(context).locale,
                  title: "App Title",
                  theme: ThemeData(
                    primarySwatch: Colors.blue,
                  ),
                  home: MapsDemo(),
                  localizationsDelegates: [
                    AppTranslationsDelegate(
                      LocaleProvider.of(context).supportedLanguagesCodes,
                    ),
                    GlobalMaterialLocalizations.delegate,
                    GlobalWidgetsLocalizations.delegate,
                  ],
                  supportedLocales: LocaleProvider.of(context).supportedLocales,
                );
              },
            );
          },
        ),
      ),
    );
  }