flutter实现语言的国际化
在Flutter中实现语言的国际化,通常使用intl
包和flutter_localizations
。以下是实现国际化的基本步骤和示例代码:
- 添加
pubspec.yaml
依赖:
dependencies:
flutter:
sdk: flutter
intl: ^0.17.0
dev_dependencies:
flutter_test:
sdk: flutter
intl_translation: ^0.17.11
- 在项目根目录下创建一个
lib
文件夹,然后在其中创建一个l10n
文件夹。 - 在
l10n
文件夹中创建一个messages_all.dart
文件,用于生成所有的语言翻译。 - 创建一个
intl_messages.arb
(或其他名称,但需要与代码中的一致),用于英语翻译。 - 创建一个
intl_localizations.dart
文件,用于定义本地化的代码。
示例代码:
pubspec.yaml
(依赖配置):
dependencies:
flutter:
sdk: flutter
intl: ^0.17.0
dev_dependencies:
flutter_test:
sdk: flutter
intl_translation: ^0.17.11
lib/l10n/intl_messages.arb
:
{
"helloWorld": "Hello World"
}
lib/l10n/intl_localizations.dart
:
import 'package:intl/intl.dart';
// 继承此类以支持国际化
class MyLocalizations {
static MyLocalizations of(BuildContext context) {
return Localizations.of<MyLocalizations>(context, MyLocalizations);
}
String get helloWorld;
}
class MyLocalizationsDelegate extends LocalizationsDelegate<MyLocalizations> {
const MyLocalizationsDelegate();
@override
bool isSupported(Locale locale) => ['en', 'es', 'ar'].contains(locale.languageCode);
@override
Future<MyLocalizations> load(Locale locale) {
// 使用Intl的messageLookup方法
final String name = 'intl/messages_${locale.languageCode}.arb';
final messages = MessageLookup();
// 使用Flutter的window.defaultLocale设置
return initializeMessages(locale.languageCode).then((_) {
return new MyLocalizations();
});
}
@override
bool shouldReload(MyLocalizationsDelegate old) => false;
}
// 使用
// MyLocalizations.of(context).helloWorld
lib/main.dart
:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'l10n/intl_localizations.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Intl',
localizationsDelegates: [
MyLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'),
评论已关闭