隨着flutter_i18n組件的做者再也不維護,IDE中的插件已被做者從插件市場中下架.原先使用該方案的FunAndroid項目採用了新的Flutter Intl方案android
該方案沒有flutter_i18n方案成熟,在開發中,IDE的插件也尚未開源.在使用中還須要開發者跟隨項目作一些適配,好比下邊會提到的對
簡繁體
和supportedLocales
的一些特殊處理git
確保Android Studio 或 VScode安裝有Flutter Intl插件github
目前AS安裝Flutter插件會自動捆綁安裝該插件xcode
在pubspec.yaml
中添加flutter_localizations
依賴並執行packages get
bash
# 國際化
flutter_localizations:
sdk: flutter
複製代碼
在菜單中找到Tools
,選擇Flutter Intl
,點擊Init for the project
app
init結束後,pubspec.yaml中會自動增長如下字段less
flutter_intl:
enabled: true
複製代碼
lib
目錄下會新增generated
和l10n
兩個目錄.ide
新增語言(好比中文)post
zh
,en
,生成arb文件
若是存在地區,相似漢語下有大陸的簡體
zh_CN
,港臺的繁體zh_HK
和zh_TW
學習
lib/generated/intl/
目錄下會生成新的messages_xx.dart
MaterialApp
中配置supportedLocales
和localizationsDelegates
localizationsDelegates
,加入由Intl
插件生成的S.delegate
和SDK組件庫的delegatesupportedLocales
須要手動將en
設置爲第一項,保證無適配對應locale時,en爲默認選項.(此到處理並不優雅)localeResolutionCallback
回調中手動處理簡繁體如下爲示例
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
// 講en設置爲第一項,沒有適配語言時,英語爲首選項
supportedLocales: [const Locale('en', ''), ...S.delegate.supportedLocales],
// 插件目前不完善手動處理簡繁體
localeResolutionCallback: (locale, supportLocales) {
// 中文 簡繁體處理
if (locale?.languageCode == 'zh') {
if (locale?.scriptCode == 'Hant') {
return const Locale('zh', 'HK'); //繁體
} else {
return const Locale('zh', 'CN'); //簡體
}
}
return null;
},
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
複製代碼
普通使用
{"content": "內容"}
S.of(context).content
複製代碼
佔位
{"welcome": "welcome {name}"}
S.of(context).welcome("phoenixsky")
複製代碼
重複佔位
{"goodStudy": "{good}{good}學習,{day}{day}向上"}
S.of(context).goodStudy("好", "天")
複製代碼
複數形式
{"getMessageTips": "{howMany, plural, zero{You have no message} one{You have 1 message} other{You have {howMany} messages}}"}
S.of(context).getMessageTips(2)
複製代碼
更多使用方式見intl | Dart Package