如何使用flutter_localizations实现数字的多语言转换?
实现数字的Locale格式化显示
1. 保留arb文件基础配置
你的app_en.arb配置可以保留,建议把描述更清晰些:
"digits": "Formatted number: {number}", "@digits": { "description": "Displays a number formatted per the current locale", "placeholders": { "number": { "type": "num" } } }
其他语言的arb文件(如app_zh.arb、app_es.arb)只需保留对应语言的字符串,比如中文arb里写"digits": "格式化数字:{number}"即可,占位符配置无需重复定义。
2. 添加intl依赖
Flutter处理本地化数字格式化需要用到intl包,在pubspec.yaml中添加:
dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: ^0.18.1 # 可替换为最新版本
3. 代码中完成数字格式化与本地化调用
在需要显示数字的页面,先获取当前Locale,再用NumberFormat处理数字,最后传入本地化字符串:
import 'package:intl/intl.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; // 示例:用户输入的数字 double userInput = 123456.789; // 获取当前页面的Locale Locale currentLocale = Localizations.localeOf(context); // 根据Locale生成格式化实例 NumberFormat numberFormatter = NumberFormat.decimalPattern(currentLocale.languageCode); // 执行格式化 String formattedNum = numberFormatter.format(userInput); // 调用本地化字符串 String displayText = AppLocalizations.of(context)!.digits(formattedNum);
4. 自定义格式化规则(可选)
如果需要特定格式,可调整NumberFormat的构造方式:
- 固定保留2位小数:
NumberFormat("#.00", currentLocale.languageCode) - 货币格式:
NumberFormat.currency(locale: currentLocale.toString(), symbol: "¥")(可指定货币符号) - 百分比格式:
NumberFormat.percentPattern(currentLocale.languageCode)
关键注意点
确保App已配置本地化支持,在MaterialApp中添加相关配置:
MaterialApp( localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en'), Locale('zh'), Locale('es'), // 添加需要支持的其他Locale ], // 其他配置项 )
内容的提问来源于stack exchange,提问作者Srasti Verma
相关产品推荐
相关产品推荐

