You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart如何根据alpha-2国家代码获取本地化国家名称

解决方案

完全可以不引入任何社区第三方包实现该需求,Dart/Flutter官方内置的本地化能力已经覆盖ISO 3166-1 alpha-2国家代码到多语言名称的映射,实现逻辑和你给出的Java getDisplayCountry() 接口完全对齐。

Flutter 环境实现(无额外第三方依赖)

Flutter SDK 自带的本地化模块已经内置了全球所有国家/地区的多语言名称映射,只需要开启官方本地化配置即可使用,不需要下载任何社区第三方包。

  • 首先确认pubspec.yaml中引入官方自带的flutter_localizations(和Flutter SDK版本绑定,无需额外执行pub get下载独立包):
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  • 在App入口配置本地化代理和需要支持的语言列表:
MaterialApp(
  localizationsDelegates: const [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('en'),
    Locale('de'),
    // 按需追加其他需要支持的语言
  ],
  // 其余页面、主题等配置正常填写即可
)
  • 编写工具方法获取本地化国家名称,逻辑和Java实现完全一致:
/// [alpha2Code] 传入两位国家代码,[displayLocale] 传入要显示的目标语言Locale
String getLocalizedCountryName(String alpha2Code, Locale displayLocale) {
  // 和Java逻辑一致:构造仅带国家代码的Locale实例
  final countryLocale = Locale(alpha2Code);
  // 调用内置方法返回对应语言的国家名称
  return countryLocale.getDisplayCountry(displayLocale);
}

// 使用示例
void testCountryName() {
  const countryCodes = ["DE", "CH", "AT"];

  // 设备语言为英语时
  const enLocale = Locale('en');
  print(countryCodes.map((e) => getLocalizedCountryName(e, enLocale)).toList());
  // 输出: [Germany, Switzerland, Austria]

  // 设备语言为德语时
  const deLocale = Locale('de');
  print(countryCodes.map((e) => getLocalizedCountryName(e, deLocale)).toList());
  // 输出: [Deutschland, Schweiz, Österreich]
}

如果需要自动跟随设备语言,直接把WidgetsBinding.instance.platformDispatcher.locale作为displayLocale参数传入即可,不需要手动判断语言。

纯Dart环境实现(非Flutter场景)

如果是纯Dart命令行/服务端场景,只需要引入Dart官方维护的intl标准库(不属于社区第三方包)即可实现:

  • 在pubspec.yaml添加官方依赖:
dependencies:
  intl: any
  • 编写实现代码:
import 'package:intl/locale.dart';

String getLocalizedCountryName(String alpha2Code, String languageTag) {
  final countryLocale = Locale.fromSubtags(countryCode: alpha2Code);
  final displayLocale = Locale.parse(languageTag);
  return countryLocale.getDisplayCountry(displayLocale);
}

void main() {
  const countryCodes = ["DE", "CH", "AT"];
  print(countryCodes.map((e) => getLocalizedCountryName(e, 'en')).toList());
  print(countryCodes.map((e) => getLocalizedCountryName(e, 'de')).toList());
}

注意事项

  • 上述方案用到的所有包均为Dart/Flutter官方维护,没有引入任何第三方社区包,返回结果和Java原生接口完全一致。
  • 如果传入的目标语言没有对应的翻译资源,方法会自动fallback到英语显示,不会抛出异常。
  • 内置数据覆盖了所有ISO标准alpha-2国家代码,支持的语言范围和Flutter原生本地化支持的语言列表完全一致。

内容的提问来源于stack exchange,提问作者Nao Kreuzeder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:45:40