使用easy_localization 实现Flutter的APP本地化

关于本地化, Flutter官方有解决方案,但自认为使用起来不是特别方便。推荐使用Easy_Localization 。

  1. 快速集成:
    pubspec.yaml文件中
dependencies:
    easy_localization: ^3.0.0

flutter:
  assets:
    - assets/translations/
  1. 创建相应的语言资源文件
assets
└── translations
    ├── {languageCode}.{ext}                  //仅languageCode
    ├── {languageCode}-{countryCode}.{ext}    
    ├── {languageCode}-{scriptCode}-{countryCode}.{ext}    //or full locale code
    └── {languageCode}-{scriptCode}.{ext}    //

创建的资源文件与下面程序中设置的支持语言一一对应。
例如:

assets
└── translations
    ├── en.json
    ├── zh-TW.json   
    ├── zh-Hant-HK.json
    └── zh-Hant.json

文件内容:以 en.json为例

{"title":"This is a title"}
  1. 配置Easy_Localization
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:easy_localization/easy_localization.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  
  runApp(
    EasyLocalization(
      supportedLocales: [
        Locale('en'),
        Locale('zh', 'TW'),
        Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'),
        Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'),
        Locale('zh'),
      ],
      path: 'assets/translations', // <-- change the path of the translation files 
      fallbackLocale: Locale('en', 'US'),
      child: MyApp()
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      home: MyHomePage()
    );
  }
}
  1. 初始化
void main() async{
  // ...
  // Needs to be called so that we can await for EasyLocalization.ensureInitialized();
  WidgetsFlutterBinding.ensureInitialized();

  await EasyLocalization.ensureInitialized();
  // ...
  runApp(....)
  // ...
}
  1. 使用
Text('title').tr() //Text widget
print('title'.tr()); //String
var title = tr('title') //Static function

注意: 如果想适配 繁体,可能需要至少配置 zh-Hant.json
因为 iOS安卓上有可能会出现 多种带有地区的言语类型,比如: 繁体台湾、繁体香港等多种繁体,如果不需要针对每一个地区的语言的话,只要设置zh-Hant.json

你可能感兴趣的:(使用easy_localization 实现Flutter的APP本地化)