Flutter国际化与本地化插件adaptive_locale的使用
Flutter国际化与本地化插件adaptive_locale的使用
通过Damian Aldair撰写。
受Adaptive Theme启发。
这是在你的Flutter应用中处理多语言最简单的方法。它允许你动态设置语言环境,获取正在使用的语言环境以及所有支持的语言环境。它还能够在应用重启后保留语言环境更改。
开始使用
在你的pubspec.yaml
文件中添加以下依赖:
dependencies:
adaptive_locale: <latest_version>
推荐使用
使用如flutter_localizations
和intl
这样的应用国际化包。
dependencies:
flutter_localizations:
sdk: flutter
intl: <latest_version>
初始化
导入该包:
import 'package:adaptive_locale/adaptive_locale.dart';
确保正确初始化包:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdaptiveLocale.ensureInitialized();
runApp(const MyApp());
}
你需要将你的MaterialApp
或CupertinoApp
包裹在AdaptiveLocale
中以便管理语言环境。
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return AdaptiveLocale(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (localizationsDelegates, supportedLocales, currentLocale) {
return MaterialApp(
localizationsDelegates: localizationsDelegates,
supportedLocales: supportedLocales,
locale: currentLocale,
title: 'Adaptive Locale Example',
home: const Screen1(),
);
},
);
}
}
现在,按照上述步骤初始化你的应用。管理语言环境非常简单。
获取所有支持的语言环境
final Iterable<Locale> locales = AdaptiveLocale.of(context).supportedLocales;
获取当前语言环境
final Locale? locale = AdaptiveLocale.of(context).locale;
如果locale
为null
,则表示语言环境是根据系统设置的。
设置要使用的语言环境
AdaptiveLocale.of(context).locale = const Locale('es');
如果要设置的语言环境不在支持的范围内,则会失败。建议先检查AdaptiveLocale.of(context).supportedLocales
。
如果你设置为null
,则表示它将使用系统特定的语言环境。
警告
此包内部使用shared_preferences插件来持久化语言环境更改。如果你的应用使用了shared_preferences(通常情况下),在登出或注销时清除
shared_preferences
可能会清除这些偏好设置。如果不希望清除这些偏好设置,请小心不要清除它们。
你可以使用AdaptiveLocale.prefKey
来排除它,当你清除所有偏好设置时。
或者,你可以在清除偏好设置后调用AdaptiveLocale.of(context).persist()
方法使其再次可持久化,如下所示:
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
AdaptiveLocale.of(context).persist();
完整示例
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdaptiveLocale.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return AdaptiveLocale(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (localizationsDelegates, supportedLocales, currentLocale) {
return MaterialApp(
localizationsDelegates: localizationsDelegates,
supportedLocales: supportedLocales,
locale: currentLocale,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
debugShowCheckedModeBanner: false,
title: 'Adaptive Locale Example',
home: const Screen1(),
);
},
);
}
}
class Screen1 extends StatelessWidget {
const Screen1({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
final loc = AppLocalizations.of(context);
const packageName = 'adaptive_locale';
const dev = 'Damian Aldair';
return Scaffold(
appBar: AppBar(
title: Text(loc.example),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
packageName,
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
),
),
Text(loc.developedBy(dev)),
const SizedBox(height: 50.0),
ElevatedButton(
child: Text(loc.nextScreen),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const Screen2()),
),
),
],
),
),
);
}
}
class Screen2 extends StatelessWidget {
const Screen2({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
final loc = AppLocalizations.of(context);
final localeManager = AdaptiveLocale.of(context);
return Scaffold(
appBar: AppBar(
title: Text(loc.example),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 50.0),
child: Text(
localeManager.locale?.toLanguageTag() ?? loc.system,
style: const TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
),
),
),
ListTile(
title: Text(loc.select),
trailing: PopupMenuButton<Locale>(
itemBuilder: (BuildContext context) {
return localeManager.supportedLocales
.map((locale) => PopupMenuItem<Locale>(
value: locale,
child: Text(locale.toLanguageTag()),
))
.toList();
},
onSelected: (Locale locale) {
localeManager.locale = locale;
},
),
),
TextButton(
child: Text(loc.system),
onPressed: () {
localeManager.locale = null;
},
),
],
),
),
);
}
}
更多关于Flutter国际化与本地化插件adaptive_locale的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter国际化与本地化插件adaptive_locale的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用adaptive_locale
插件来实现国际化与本地化的代码示例。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加adaptive_locale
依赖:
dependencies:
flutter:
sdk: flutter
adaptive_locale: ^0.x.x # 请替换为最新版本号
2. 配置本地化资源
在android/app/src/main/res
目录下创建values-xx
文件夹,其中xx
是语言代码(如values-en
表示英文,values-zh
表示中文)。在每个文件夹中创建一个strings.xml
文件,内容如下:
values/strings.xml
(默认语言)
<resources>
<string name="app_name">My App</string>
<string name="welcome_message">Welcome!</string>
</resources>
values-en/strings.xml
(英文)
<resources>
<string name="app_name">My App</string>
<string name="welcome_message">Welcome!</string>
</resources>
values-zh/strings.xml
(中文)
<resources>
<string name="app_name">我的应用</string>
<string name="welcome_message">欢迎!</string>
</resources>
对于iOS,你需要在ios/Runner
目录下创建Base.lproj
和对应的语言文件夹(如en.lproj
, zh.lproj
),并在这些文件夹中添加Localizable.strings
文件。
Base.lproj/Localizable.strings
"app_name" = "My App";
"welcome_message" = "Welcome!";
en.lproj/Localizable.strings
"app_name" = "My App";
"welcome_message" = "Welcome!";
zh.lproj/Localizable.strings
"app_name" = "我的应用";
"welcome_message" = "欢迎!";
3. 设置Flutter项目
在你的Flutter项目的lib
目录下创建一个locales
文件夹,并在其中创建一个app_localizations.dart
文件,内容如下:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:adaptive_locale/adaptive_locale.dart';
class AppLocalizations {
static Future<AdaptiveLocale> load(Locale locale) {
return AdaptiveLocale.load(
locale,
fallbackLocale: Locale('en', 'US'),
resources: {
Locale('en', 'US'): AppLocalizationEn(),
Locale('zh', 'CN'): AppLocalizationZh(),
},
);
}
}
class AppLocalizationEn implements AdaptiveLocaleResources {
@override
String get appName() => 'My App';
@override
String get welcomeMessage() => 'Welcome!';
}
class AppLocalizationZh implements AdaptiveLocaleResources {
@override
String get appName() => '我的应用';
@override
String get welcomeMessage() => '欢迎!';
}
// 抽象类定义
abstract class AdaptiveLocaleResources {
String get appName();
String get welcomeMessage();
}
4. 使用插件
在你的主应用程序文件(如main.dart
)中,使用adaptive_locale
插件:
import 'package:flutter/material.dart';
import 'package:adaptive_locale/adaptive_locale.dart';
import 'locales/app_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AdaptiveLocale(
supportedLocales: [Locale('en', 'US'), Locale('zh', 'CN')],
useDeviceLocale: true,
builder: (context, locale) async {
final adaptiveLocale = await AppLocalizations.load(locale);
return MaterialApp(
title: adaptiveLocale.appName,
locale: locale,
supportedLocales: adaptiveLocale.supportedLocales,
localizationsDelegates: [
adaptiveLocale.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
home: MyHomePage(adaptiveLocale: adaptiveLocale),
);
},
);
}
}
class MyHomePage extends StatelessWidget {
final AdaptiveLocale adaptiveLocale;
MyHomePage({required this.adaptiveLocale});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(adaptiveLocale.appName),
),
body: Center(
child: Text(adaptiveLocale.welcomeMessage),
),
);
}
}
这样,你就完成了Flutter项目中adaptive_locale
插件的使用,实现了国际化与本地化。根据设备的语言设置,应用将自动显示相应的语言内容。