關(guān)于本地化, Flutter官方有解決方案,但自認(rèn)為使用起來不是特別方便。推薦使用Easy_Localization 。
- 快速集成:
在pubspec.yaml文件中
dependencies:
easy_localization: ^3.0.0
flutter:
assets:
- assets/translations/
- 創(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"}
- 配置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()
);
}
}
- 初始化
void main() async{
// ...
// Needs to be called so that we can await for EasyLocalization.ensureInitialized();
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
// ...
runApp(....)
// ...
}
- 使用
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