Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get currency and currency symbol in flutter by country code?

Tags:

flutter

I'm converting my app from Java(Android) to Flutter(Dart) and I can't find a method to get the currency from context or from a country code.

Code in Java:

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

Code in Dart:

Locale locale = Localizations.localeOf(context);

String country = locale.countryCode;
like image 333
Matteo Antolini Avatar asked Nov 08 '19 11:11

Matteo Antolini


4 Answers

intl package does the trick

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
}
like image 136
Bülent Hacioglu Avatar answered Oct 20 '22 02:10

Bülent Hacioglu


While the accepted answer does work if your app supports the user's locale, it doesn't work if you didn't explicitly add support for the user's locale.

Instead you can use Platform.localeName from the dart:io package which will take the locale of the device itself.

For Example:

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

String getCurrency() {
  var format = NumberFormat.simpleCurrency(locale: Platform.localeName);
  return format.currencySymbol;
}
like image 25
Maxim Janssens Avatar answered Oct 20 '22 00:10

Maxim Janssens


By default the country symbol is in dollar, to get your local symbol add the name property like this (for Nigeria - Naira):

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

String getCurrency() {
  var format = NumberFormat.simpleCurrency(locale: Platform.localeName, name: 'NGN');
  return format.currencySymbol;
}
like image 8
Jereson Avatar answered Oct 20 '22 01:10

Jereson


You can get currency code using currency_pickers by giving it user country code.

CurrencyPickerUtils.getCountryByIsoCode('PK').currencyCode.toString() // PKR
CurrencyPickerUtils.getCountryByIsoCode('US').currencyCode.toString() // USD
like image 4
Rana Hyder Avatar answered Oct 20 '22 02:10

Rana Hyder