美文网首页
9 Flutter国际化手动配置

9 Flutter国际化手动配置

作者: Jean_Lina | 来源:发表于2022-01-04 10:29 被阅读0次

    (1) yaml文件添加依赖

    dependencies:
      flutter:
        sdk: flutter
      flutter_localizations:
        sdk: flutter
    

    (2) 创建类文件:数据类

    
    class YYYLocalizations {
      
      YYYLocalizations(this.locale);
    
      Locale? locale;
    
      static YYYLocalizations of(BuildContext context) {
        return Localizations.of(context, YYYLocalizations);
      }
    
      /// 国际化数据data字典
      Map<String, Map<String, String>> data = {};
    
      /// 从json中加载数据
      Future<void> loadI18nJson() async {
        String path = "assets/json/i18n.json";
        final result = await rootBundle.loadString(path);
        Map<String, dynamic> dataDict = json.decode(result);
        data = dataDict.map((key, value) {
          return MapEntry(key, value.cast<String, String>());
        });
      }
    
      /// 手写对应字段的get方法
      String? get title1 {
        return data[locale?.languageCode]?["title1"];
      }
    
      String? get title2 {
        return data[locale?.languageCode]?["title2"];
      }
    
      String? get title3 {
        return data[locale?.languageCode]?["title3"];
      }
    
      String? get title4 {
        return data[locale?.languageCode]?["title4"];
      }
    
      String? get title5 {
        return data[locale?.languageCode]?["title5"];
      }
    }
    

    (3) 创建类文件:代理delegate类

    class YYYLocalizationDelegate extends LocalizationsDelegate<YYYLocalizations> {
      static YYYLocalizationDelegate delegate = YYYLocalizationDelegate();
    
      /// 支持的语言编码
      @override
      bool isSupported(Locale locale) {
        return ["zh", "en"].contains(locale.languageCode);
      }
    
      /// 加载国际化数据并返回
      @override
      Future<YYYLocalizations> load(Locale locale) async {
        YYYLocalizations localizations = YYYLocalizations(locale);
        await localizations.loadI18nJson();  //异步加载数据
        return localizations;
        //return SynchronousFuture(YYYLocalizations(locale)); //同步本地数据
      }
    
      /// 是否重新加载数据资源
      @override
      bool shouldReload(covariant LocalizationsDelegate<YYYLocalizations> old) {
        return false;
      }
    }
    

    (4) MaterialApp中进行配置

    MaterialApp(
          supportedLocales: [
            Locale('zh'),
            Locale("en"),
          ],
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            YYYLocalizationDelegate.delegate, //手动创建的
          ],
        );
    

    (6) 不同界面中获取国际化配置的内容

    YYYLocalizations.of(context).bottomBarTitle1;
    
    YYYLocalizations.of(context).bottomBarTitle2;
    
    YYYLocalizations.of(context).bottomBarTitle3;
    

    相关文章

      网友评论

          本文标题:9 Flutter国际化手动配置

          本文链接:https://www.haomeiwen.com/subject/ticnqrtx.html