在移动应用开发中,多语言支持(国际化)是一个重要的功能。Flutter 提供了多种国际化解决方案,本文将对比三种主流方式:原生的 flutter_localizations
、社区库 easy_localization
,以及我们最终选择的 GetX
(主要是项目已经引入了GetX,本来想用easy_localization的)。
优点:
intl
包结合实现复杂的格式化(日期、货币等)。缺点:
# pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.18.1
import 'package:flutter_localizations/flutter_localizations.dart';
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('en'),
Locale('zh'),
],
)
优点:
缺点:
dependencies:
easy_localization: ^3.0.3
EasyLocalization(
supportedLocales: [Locale('en'), Locale('zh')],
path: 'assets/langs',
fallbackLocale: Locale('en'),
child: MyApp(),
);
// assets/langs/en.json
{
"hello": "Hello"
}
// assets/langs/zh.json
{
"hello": "你好"
}
优点:
缺点:
intl
的高级格式化功能(可手动处理)。flutter create getx_i18n_demo
cd getx_i18n_demo
编辑 pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
get: ^4.6.6
然后执行:
flutter pub get
在 lib/langs/messages.dart
中:
import 'package:get/get.dart';
class Messages extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'en_US': {
'hello': 'Hello',
'switch_language': 'Switch Language',
'title': 'Home Page',
},
'zh_CN': {
'hello': '你好',
'switch_language': '切换语言',
'title': '首页',
}
};
}
修改 lib/main.dart
:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'langs/messages.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
translations: Messages(), // 多语言配置
locale: Locale('zh', 'CN'), // 默认语言
fallbackLocale: Locale('en', 'US'),
home: HomePage(),
);
}
}
在 lib/home_page.dart
中:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('title'.tr)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('hello'.tr, style: TextStyle(fontSize: 24)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
final isEnglish = Get.locale?.languageCode == 'en';
final newLocale = isEnglish ? const Locale('zh', 'CN') : const Locale('en', 'US');
Get.updateLocale(newLocale);
},
child: Text('switch_language'.tr),
)
],
),
),
);
}
}
并记得在 main.dart
中导入它:
import 'home_page.dart';
.tr
自动翻译。lib/
├── home_page.dart
├── langs/
│ └── messages.dart
└── main.dart