flutter l10n如何传递参数
在Flutter中使用l10n进行国际化时,如何传递动态参数到本地化字符串?例如,我想在显示"欢迎回来,{username}"时,将username替换为实际用户名字符串。目前官方文档只展示了简单文本的本地化,不清楚如何在arb文件中定义带参数的字符串以及在代码中正确传递这些参数。能否提供一个具体示例说明如何实现?
2 回复
在Flutter l10n中传递参数,需在.arb文件中使用占位符,如{param},然后在Dart代码中调用生成的本地化方法并传入参数。例如:AppLocalizations.of(context)!.hello('John')。
更多关于flutter l10n如何传递参数的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在 Flutter 的本地化(l10n)中传递参数,可以通过以下方式实现:
1. 定义带参数的本地化方法
在 ARB 文件或直接在 Dart 类中定义带占位符的字符串:
ARB 文件示例 (app_en.arb):
{
"welcomeMessage": "Hello {name}, you have {count} messages",
"@welcomeMessage": {
"description": "欢迎消息",
"placeholders": {
"name": {},
"count": {}
}
}
}
2. 生成本地化类
运行 flutter gen-l10n 命令生成对应的本地化类,会生成类似的方法:
String welcomeMessage(String name, int count);
3. 在代码中使用
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
AppLocalizations.of(context)!.welcomeMessage('John', 5),
);
}
}
4. 手动实现(不使用代码生成)
如果不使用 ARB 文件,可以手动创建本地化类:
class AppLocalizations {
final Locale locale;
AppLocalizations(this.locale);
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
}
String welcomeMessage(String name, int count) {
switch (locale.languageCode) {
case 'zh':
return '你好 $name,你有 $count 条消息';
default:
return 'Hello $name, you have $count messages';
}
}
}
注意事项:
- 确保在
pubspec.yaml中正确配置 l10n - 参数顺序和类型必须与定义一致
- 使用前检查
AppLocalizations.of(context)是否为 null
这种方式可以灵活地在不同语言的字符串中传递动态参数。

