How to add support for all locale's currency symbols in a flutter app

Viewed 2701

I would like to show the user the currency symbol of their current locale. The locale and currency symbol can easily be retrieved with:

import 'package:intl/intl.dart';    
var localeString = Localizations.localeOf(context).toString();
var _currencySymbol = NumberFormat.simpleCurrency(locale: localeString).currencySymbol;

The problem is that to retrieve the user's currency symbol the app has to support the user's locale. For eg. if you would like to show a user in South Africa a currency in South African Rands the Locale('en', 'ZA') has to be added to the current supported locales.

Adding support for all countries' locales in the supported locales list:

supportedLocales: [
    const Locale('en', 'US'), // USD
    const Locale('en', 'ZA'), // ZAR
    const Locale('en', 'AU'), // AUD
    //..... All other locales
  ],

does not seem feasible and won't have support for new countries being added to the flutter intl list. Is there an easier/better way to add support for all countries' locales or to display all locales' currency symbols?

1 Answers

The currency code along with some other localization info is stored in a file called number_symbols_data.dart as a huge Map.

you can import the file from Intl library as follows:

import 'package:intl/number_symbols_data.dart';

then you can get the currency code by:

numberFormatSymbols['ar_EG'].DEF_CURRENCY_CODE .

note: replace ar_EG with the required local.

If you want to support all Locales you can use

supportedLocales: numberFormatSymbols.keys
      .where((key)=>key.toString().contains('_'))
      .map((key)=> key.toString().split('_'))
      .map((split)=>Locale(split[0],split[1])).toList(),

Edit: after careful investigation the previous code will only support locales which has _<COUNTRY_CODE> so to support other locals the code should be modified like so

supportedLocales: numberFormatSymbols.keys
          //.where((key)=>key.toString().contains('_'))
          .map((key)=> key.toString().split('_'))
          .map((split)=>Locale(split[0],split.length == 1? null:split[1])).toList(),
Related