Flutter - 国际化

国际化

  • pubspec添加依赖
    dependencies:
      flutter:
        sdk: flutter
      flutter_localizations:
        sdk: flutter
  • 设置MaterialApp
  1. 在localizationsDelegates中指定哪些Widget需要进行国际化
       localizationsDelegates: [
              /// 指定本地化的字符串和一些其他的值
              GlobalMaterialLocalizations.delegate,
              /// 对应的Cupertino风格
              GlobalCupertinoLocalizations.delegate,
              /// 指定默认的文本排列方向, 由左到右或由右到左
              GlobalWidgetsLocalizations.delegate
            ]
  1. supportedLocales指定要支持哪些国际化
      supportedLocales: [
              Locale('zh'),
              Locale('en'),
            ]

iOS的配置

  • 在info.plist配置


    image.png
对自己写的字符串进行国际化
  1. 写个本地化管理类
数据:
{
  "en": {
    "title": "home",
    "subTitle": "hello world",
  },
  "zh": {
    "title": "首页",
    "subTitle": "你好 世界",
  }
}


    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    class HJLocalManager {
    
      final Locale local;
      HJLocalManager(this.local);
   
      /// 异步加载json文件
      Future loadLocalValues() async {
        final jsonStr = await rootBundle.loadString('assets/json/localValues.json');
    
        /// json -> map
        Map result = json.decode(jsonStr);
        /// 遍历每个键值对
        _localValues = result.map((key, value) {
         
          return MapEntry(key, value.cast());
        });
        return true;
      }
    
      String? get title {
        return _localValues[local.languageCode]?['title'];
      }
      String? get subTitle {
        return _localValues[local.languageCode]?['subTitle'];
      }
    
      ///静态方法
      static HJLocalManager of(BuildContext context) {
        return Localizations.of(context, HJLocalManager);
      }
    }
  1. 定义一个对象的Delegate类,实现重写方法,传入localizationsDelegates
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/foundation.dart';
    import 'package:internationalization/HJLocalizations/HJLocalManager.dart';
    
    class HJLocalDelegate extends LocalizationsDelegate{
      @override
      ///当前环境的Locale,是否在我们支持的语言范围
      bool isSupported(Locale locale) {
        // TODO: implement isSupported
        return ['en','zh'].contains(locale.languageCode);
      }
    
      @override
      /// 当Locale发生改变时(语言环境),加载对应的HYLocalizations资源
      Future load(Locale locale) async {
        // TODO: implement load
        //return SynchronousFuture(HJLocalManager(locale));
        final localization = HJLocalManager(locale);
        await localization.loadLocalValues();
        return localization;
      }
    
      @override
      ///当Localizations Widget重新build时,是否调用load方法重新加载Locale资源
      bool shouldReload(covariant LocalizationsDelegate old) {
        // TODO: implement shouldReload
        return false;
      }
    
      static HJLocalDelegate delegate = HJLocalDelegate();
    }
  1. 使用
    localizationsDelegates: [
            /// 指定本地化的字符串和一些其他的值
            GlobalMaterialLocalizations.delegate,
            /// 对应的Cupertino风格
            GlobalCupertinoLocalizations.delegate,
            /// 指定默认的文本排列方向, 由左到右或由右到左
            GlobalWidgetsLocalizations.delegate,
            /// 加入自定义的delegate
            HJLocalDelegate.delegate
          ]
          
          
    
    Scaffold(
          appBar: AppBar(
            title: Text(HJLocalManager.of(context).title??''),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(HJLocalManager.of(context).subTitle??'',style: TextStyle(fontSize: 20),),
                ElevatedButton(
                    onPressed: () {
                      
                    },
                    child: Text(
                      HJLocalManager.of(context).subTitle??'',
                      style: TextStyle(fontSize: 24),
                    ))
              ],
            ),
          ),
        );
工具
arb文件
  • 安装Flutter Intl插件


    image.png
  • 初始化插件


    image.png
  • 会多出一些文件

    1. generated是自动生成的dart代码
    2. I10n是对应的arb文件目录
      image.png
使用
  • 配置supportedLocales
    supportedLocales: S.delegate.supportedLocales,
  • 配置localizationsDelegates,增加S.delegate
    localizationsDelegates: [
            /// 指定本地化的字符串和一些其他的值
            GlobalMaterialLocalizations.delegate,
            /// 对应的Cupertino风格
            GlobalCupertinoLocalizations.delegate,
            /// 指定默认的文本排列方向, 由左到右或由右到左
            GlobalWidgetsLocalizations.delegate,
            HJLocalDelegate.delegate,
            S.delegate
          ]
  • 编写arb文件
{
  "title": "home",
  "text": "Tap",
  "btnText": "Pick a Time",
  "subText": "bakabaka {name}"
}
  • 使用
    S.of(context).title
  • 添加其他语言,如中文


    image.png
  • 会生成对应的文件


    image.png
  • 配置对应的中文到zh.arb即可使用

其他语法
  • 传参数配置
    {
      "title": "首页",
      "text": "点击",
      "btnText": "选择一个时间",
      "subText": "巴卡巴卡 {name}"
    }
  • 传参使用
    Text(S.of(context).subText('海贼·王路飞'))

你可能感兴趣的:(Flutter - 国际化)