使用easy_localization 實現(xiàn)Flutter的APP本地化

關(guān)于本地化, Flutter官方有解決方案,但自認(rèn)為使用起來不是特別方便。推薦使用Easy_Localization 。

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

flutter:
  assets:
    - assets/translations/
  1. 創(chuàng)建相應(yīng)的語言資源文件
assets
└── translations
    ├── {languageCode}.{ext}                  //僅languageCode
    ├── {languageCode}-{countryCode}.{ext}    
    ├── {languageCode}-{scriptCode}-{countryCode}.{ext}    //or full locale code
    └── {languageCode}-{scriptCode}.{ext}    //

創(chuàng)建的資源文件與下面程序中設(shè)置的支持語言一一對應(yīng)。
例如:

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

文件內(nèi)容:以 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安卓上有可能會出現(xiàn) 多種帶有地區(qū)的言語類型,比如: 繁體臺灣、繁體香港等多種繁體,如果不需要針對每一個地區(qū)的語言的話,只要設(shè)置zh-Hant.json

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容