Flutter Device Locale

All things Flutter

Flutter Device Locale

This is a follow up project created for the Watch Tips app demo that was created and released into the app store. Basically the app displays a generic currency value and formats it in a ‘UK’ standardised way with no currency symbol. This was OK, but if the device is used elsewhere then the currency format may well be different.

After looking around at the Flutter i18n capabilities, it look like the intl package could be used. The code already used

NumberFormat formatter = NumberFormat("##0.00");

Which would display a value like 125.56

to create a general number format. But to format to the device locale I need the locale value (i.e. “en_US”). The requirement was to extract the current device locale, not the supported locals of the running app.

As it seemed there was no simple way to do this, a Flutter Package called Devicelocale was written to return the current device locales. Using the return value from device locale meant that the formatter could be set up to automatically format the currency and use the associated currency symbol.

List locales = await platform.invokeMethod("preferredLanguages");
if (locales.length > 0) {
  formatter = NumberFormat.simpleCurrency(locale: locales[0]);

So now it will format the display and add the currency symbol, for example , if the language is set to Spanish  the display will now show  125,46 € rather than 125.46  or £ 125.46