Flutter國際化

preview.gif
集成easy_localization插件
flutter pub add easy_localization easy_logger
配置 pubspec.yaml 文件
# 創(chuàng)建 `assets/translations` 目錄
mkdir -p assets/translations
touch assets/translations/en.json
touch assets/translations/zh.json
en.json
{
"hello": "Hello World",
"title": "Flutter Demo Home Page",
"welcome_to_flutter": "Welcome to Flutter"
}
zh.json
{
"hello": "你好,世界",
"title": "Flutter 演示首頁",
"welcome_to_flutter": "歡迎來到Flutter"
}
flutter:
assets:
- assets/translations/
代碼示例
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hq_kocalization_stu/generated/locale_keys.g.dart';
import 'package:easy_logger/easy_logger.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
//設(shè)置日志級別
EasyLocalization.logger.enableLevels = [
LevelMessages.error,
LevelMessages.warning,
];
runApp(
EasyLocalization(
supportedLocales: const [Locale('zh'), Locale('en')],
path: 'assets/translations',
//是否自動(dòng)保存選擇的語言
saveLocale: true,
useOnlyLangCode: true,
// 啟動(dòng)時(shí)的默認(rèn)語言
startLocale: const Locale('zh'),
// 回退語言
fallbackLocale: const Locale('zh'),
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isZh = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(LocaleKeys.hello.tr()),
Text(LocaleKeys.title.tr()),
Text(LocaleKeys.welcome_to_flutter.tr()),
FilledButton(
onPressed: () {
setState(() {
isZh = !isZh;
// 切換語言
context.setLocale(
isZh ? const Locale('zh') : const Locale('en'),
);
});
},
child: Text(isZh ? '中文' : 'English'),
),
],
),
),
);
}
}
使用方式
- 直接字符串使用tr()方法
"hello".tr()
- 生成locale_keys.g.dart文件
flutter pub run easy_localization:generate -S ./assets/translations -f keys -o locale_keys.g.dart
Text(
LocaleKeys.hello.tr(),
),
參考
https://github.com/aissat/easy_localization?tab=readme-ov-file