【问题标题】:How to get currency and currency symbol in flutter by country code?如何通过国家代码获得货币和货币符号?
【发布时间】:2019-11-08 11:56:32
【问题描述】:

我正在将我的应用程序从 Java(Android) 转换为 Flutter(Dart),但我找不到从上下文或国家代码中获取货币的方法。

Java 代码:

String country = Locale.getDefault().getCountry();
String currency = Currency.getInstance(new Locale("", country)).getCurrencyCode();

Dart 中的代码:

Locale locale = Localizations.localeOf(context);

String country = locale.countryCode;

【问题讨论】:

标签: flutter


【解决方案1】:

intl 包可以解决问题

import 'package:intl/intl.dart';

void currency() {
    Locale locale = Localizations.localeOf(context);
    var format = NumberFormat.simpleCurrency(locale: locale.toString());
    print("CURRENCY SYMBOL ${format.currencySymbol}"); // $
    print("CURRENCY NAME ${format.currencyName}"); // USD
}

【讨论】:

  • Localizations.localeOf() 返回语言偏好,在大多数手机上它是 en_us,NumberFormat.simpleCurrency() 将为不使用美元的人返回 $
  • 但是当我们更改应用程序语言时呢?我仍然使用设备语言
  • 即使在非美元货币的位置,它仍然返回美元。我该如何解决?
  • 当你发现自己在几个月前问同样的问题时,会很沮丧
【解决方案2】:

如果您的应用支持用户的语言环境,则接受的答案确实有效,但如果您没有明确添加对用户语言环境的支持,则它不起作用。

相反,您可以使用 dart:io 包中的 Platform.localeName,它将采用设备本身的语言环境。

例如:

import 'package:intl/intl.dart';
import 'dart:io';

String getCurrency() {
  var format = NumberFormat.simpleCurrency(locale: Platform.localeName);
  return format.currencySymbol;
}

【讨论】:

  • 这对我有用。包括 Platform.localName
  • 很棒,因为它不需要上下文
  • 不能在网络上使用
【解决方案3】:

默认情况下,国家/地区符号是美元,要获取您的本地符号,请添加这样的名称属性(对于尼日利亚 - 奈拉):

import 'package:intl/intl.dart';
import 'dart:io';

String getCurrency() {
  var format = NumberFormat.simpleCurrency(locale: Platform.localeName, name: 'NGN');
  return format.currencySymbol;
}

【讨论】:

    【解决方案4】:

    您可以使用currency_pickers 获取货币代码,方法是给它用户国家代码。

    CurrencyPickerUtils.getCountryByIsoCode('PK').currencyCode.toString() // PKR
    CurrencyPickerUtils.getCountryByIsoCode('US').currencyCode.toString() // USD
    

    【讨论】:

    • 是否可以使用currency_pickers获取国家货币符号?
    【解决方案5】:

    在这个问题上搜索了很长时间后,解决我的问题的唯一解决方案是使用支持您的符号的字体。
    这是我的符号“₺”,支持它的字体是“Roboto”,您可以像这样为文本指定字体:

      Text('₺',
         style: TextStyle(
         fontFamily: 'Roboto',
          )),
    

    【讨论】:

      【解决方案6】:

      这很容易, 只需在谷歌上搜索 Country 符号,然后像这样添加文本小部件,Text( "₦20000", style: TextStyle( fontSize: 24.0, fontFamily: '' ), )

      如果您不确定支持的字体系列,则无需添加字体系列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 2012-09-04
        相关资源
        最近更新 更多