Flutter国际化
-
添加package
flutter_localizations:
sdk: flutter
intl: any
-
安装vs code插件
Flutter Intl
- 点击vs code菜单栏的View->Command Paletter
- 搜索Flutter Intl:initialize,点击执行会生成如下文件
同时在文件pubspec.yaml
中会增加代码
flutter_intl:
enabled: true
- 搜索Flutter Intl: Add locale,点击执行添加新的多语言,比如zh
- 添加不同语言的资源数据
在生成的intl_en.arb
和intl_zh.arb
文件中添加json格式数据
注意修改后记得执行命令 flutter pub get
intl_en.arb
{
"title": "Hello Flutter!"
}
intl_zh.arb
{
"title": "您好Flutter!"
}
-
添加代码
lib文件
MaterialApp
import 'package:flutter_localizations/flutter_localizations.dart';
GetMaterialApp(
debugShowCheckedModeBanner: false, // 右上角debug图标是否显示
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales: S.delegate.supportedLocales,
locale: Locale.fromSubtags(
languageCode: mobxCounterStore.useLanguage), // 设置用户自定义选择的语言
localeListResolutionCallback: (locales, supportedLocales) {
print('当前系统语言:$locales');
return Locale.fromSubtags(
languageCode: mobxCounterStore.useLanguage);
},
// localeResolutionCallback: (locale, supportedLocales) {
// print('localeResolutionCallback$locale');
// return const Locale.fromSubtags(languageCode: 'zh');
// },
)
-
切换语言
localization_demo_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:provider/provider.dart';
import 'package:terminal_flutter_demo/generated/l10n.dart';
import 'package:terminal_flutter_demo/pages/mobxpages/store/mobx_counter.dart';
class LocalizationDemoPage extends StatefulWidget {
const LocalizationDemoPage({Key? key}) : super(key: key);
@override
_LocalizationDemoPageState createState() => _LocalizationDemoPageState();
}
class _LocalizationDemoPageState extends State<LocalizationDemoPage> {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Text(S.current.title),
const SizedBox(height: 30),
Consumer<MobxCounter>(
builder: (context, mobxCounter, child) {
return Observer(
builder: (context) => SwitchListTile(
value: mobxCounter.useLanguage == 'zh',
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(mobxCounter.useLanguage),
Text(S.current.title),
],
),
onChanged: (value) {
mobxCounter.setLanguage(
value: mobxCounter.useLanguage == 'zh' ? 'en' : 'zh');
},
),
);
},
),
],
),
);
}
}