138

I want to get Timezone, language, and county Id when I run my project on my device android or iOS. It should detect Timezone, language and country Id from the location of the device.

Can I get these via the internal library?

10 Answers 10

242

Flutter locales explained

First of all, you should understand the difference between system settings and your application settings:

  • System settings - what the system provides to your app as user preferences for your information.
  • Application settings - what you decided (explicitly or implicitly) to be the application locale. You may allow your users to select any locale of your app or let Flutter to do it for you.

Getting current system preferences

Get the current default system locale

import 'dart:io';

final String defaultLocale = Platform.localeName; // Returns locale string in the form 'en_US'

Get the list of system locales

import 'package:flutter/material.dart';

final List<Locale> systemLocales = WidgetsBinding.instance.window.locales; // Returns the list of locales that user defined in the system settings.

or

import 'dart:ui';

final List<Locale> systemLocales = window.locales;

Locale of your application

The MaterialApp widget supports localization. It accepts the list of locales that you decided your app supports. That means you should explicitly define them in the widget initialization in the supportedLocales property and provide so-called "localization delegates" that will do the actual translation to a selected locale (the localizationsDelegates property). Providing delegates is required if your app supports any other locales except en_US. When you request an application locale you will get an exact value from the list of supportedLocales.

Getting your application locale

final Locale appLocale = Localizations.localeOf(context);

This works only when the MaterialApp widget is already initialized. You can not use it before the MaterialApp initialization. Obviously, if your app widget is not initialized, you can not get its locale. To use it, you must call this expression in a child component's build method. For example:

void main() async {
  runApp(
    MaterialApp(
      title: 'MyApp',
      home: MyApp(),
    )
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Show the name of the current application locale
    return Text(Localizations.localeOf(context).toString());
  }
}

This will print the en_US text on the screen (because this is the default locale and we did not provide anything else). It doesn't matter what the system locale settings are because we didn't define explicitly any locale for our app in this example and thus it returns the default one.

Catch system locale changes

To be able to react on system locale changes, you should use a stateful widget that implements the WidgetsBindingObserver mixin and define the didChangeLocales method that will be called on system locale changes:

  @override
  void didChangeLocales(List<Locale> locale) {
    // This is run when system locales are changed
    super.didChangeLocales(locale);
    setState(() {
      // Do actual stuff on the changes
    });
  }

Full example

To summarize all the above, here is the visual example of getting locales on startup and reacting on system settings changes:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Get the initial locale values
  final String defaultSystemLocale = Platform.localeName;
  final List<Locale> systemLocales = WidgetsBinding.instance.window.locales;

  // Define locales that our app supports (no country codes, see comments below)
  final appSupportedLocales = <Locale>[
    Locale('ru'),
    Locale('en'),
  ];

  final MyApp myApp = MyApp(defaultSystemLocale, systemLocales);

  runApp(
    MaterialApp(
      title: 'MyApp',
      home: myApp,
      supportedLocales: appSupportedLocales,
      localizationsDelegates: [
        // These are default localization delegates that implement the very basic translations for standard controls and date/time formats.
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
    )
  );
}

class MyApp extends StatefulWidget {
  // Store initial locale settings here, they are unchanged
  final String initialDefaultSystemLocale;
  final List<Locale> initialSystemLocales;

  MyApp(this.initialDefaultSystemLocale, this.initialSystemLocales);

  @override
  _MyAppState createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  // Store dynamic changeable locale settings here, they change with the system changes
  String currentDefaultSystemLocale;
  List<Locale> currentSystemLocales;

  // Here we read the current locale values
  void setCurrentValues() {
    currentSystemLocales = WidgetsBinding.instance.window.locales;
    currentDefaultSystemLocale = Platform.localeName;
  }

  @override
  void initState() {
    // This is run when the widget is first time initialized
    WidgetsBinding.instance.addObserver(this); // Subscribe to changes
    setCurrentValues();
    super.initState();
  }

  @override
  void didChangeLocales(List<Locale> locale) {
    // This is run when system locales are changed
    super.didChangeLocales(locale);
    // Update state with the new values and redraw controls
    setState(() {
      setCurrentValues();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text('Initial system default locale: ${widget.initialDefaultSystemLocale}.'),
          Text('Initial language code: ${widget.initialDefaultSystemLocale.split('_')[0]}, country code: ${widget.initialDefaultSystemLocale.split('_')[1]}.'),
          Text('Initial system locales:'),
          for (var locale in widget.initialSystemLocales) Text(locale.toString()),
          Text(''),
          Text('Current system default locale: ${currentDefaultSystemLocale}.'),
          Text('Current system locales:'),
          for (var locale in currentSystemLocales) Text(locale.toString()),
          Text(''),
          Text('Selected application locale: ${Localizations.localeOf(context).toString()}.'),
          Text(''),
          Text('Current date: ${Localizations.of<MaterialLocalizations>(context, MaterialLocalizations).formatFullDate(DateTime.now())}.'),
          Text('Current time zone: ${DateTime.now().timeZoneName} (offset ${DateTime.now().timeZoneOffset}).'),
        ],
      ),
    );
  }
}

The supported locales are defined without country codes to show you how the selection of the current app locale works. Internally, the MaterialApp widget is comparing the list of locales supported by the app with the list of user preferences passed by the system and selects the most appropriate one.

Let's assume that we have the following list of system locales (en_US, en_GB, ru_RU):

** Click on thumbnail to see the full screenshot.

initial list of locales

Our app will look like this on startup:

initial app state

We see that initial and current values obviously the same. The app selected the en locale as its current locale.

Now let's change the list of locales to the following, moving the en_GB locale to top making it the default system locale:

UK locale on top

The app will reflect this change:

app with the UK locale

The app obviously still selects the en locale as its current locale because it is the closest match to both en_US and en_GB locales.

Now let's change the settings to the Russian language as the default system value:

RU locale on top

Our app will reflect this change:

app with the RU locale

Now you can see that the ru locale was selected as the app locale.

Hope this helps to understand how localization works in Flutter, how to get current values, and how to reflect system changes. The details about locale delegates are not explained because it is off-topic here.

PS: This code is tested under Android only. I think with minor changes it can be adapted to all other platforms.

3
  • your code need to be updated super.didChangeLocales and WidgetsBinding.instance.addObserver(this)
    – zakiblacki
    Dec 19, 2022 at 7:36
  • also WidgetsBinding.instance.window is deprecated. ): Aug 9 at 18:15
  • Getting the list of system locales should now be WidgetsBinding.instance.platformDispatcher.locales, as window is deprecated yesterday
115

https://flutter.io/tutorials/internationalization/#tracking-locale

Locale myLocale = Localizations.localeOf(context);

provides countryCode and languageCode

https://docs.flutter.io/flutter/dart-ui/Locale-class.html

The timezone should be available with (not tried)

DateTime.now().timeZoneName

https://docs.flutter.io/flutter/dart-core/DateTime-class.html

13
  • 12
    Thanks @Gunter, but I am getting country code "US" and language id "en", how can I get it accordingly my current location, as I am in India it should show "IND"
    – Ammy Kang
    Jun 19, 2018 at 8:57
  • 5
    Locale myLocale = Localizations.localeOf(context); does not work for me. myLocale.languageCode is always "en" May 10, 2019 at 8:18
  • 5
    When I do this, I get the error "Failed assertion", "Scope != null, a Localizations ancestor was not found". Jul 11, 2019 at 13:11
  • 5
    The reason that Localizations.localeOf(context) does not work for everyone: it gives the locale of the current context, which is derived from the system locale but has been resolved to one of the locales in supportedLocales. This is a parameter passed to the MaterialApp or WidgetsApp widget, and the default is only [en_US]. Using WidgetsBinding.instance.window.locale gives you the raw thing.
    – Thomas
    May 15, 2020 at 8:30
  • 3
    If you guys are on iOS, do not actually forget to add supported languages in your info.plist otherwise you won't have it available.
    – schankam
    Jun 23, 2020 at 8:09
35

you can use

import 'dart:io' show Platform;

String languageCode = Platform.localeName.split('_')[0];
String countryCode = Platform.localeName.split('_')[1];
4
  • This doesn't work for me if I change the iOS Simulator to US Spanish. I still get "en", "US". May 29, 2020 at 12:00
  • 2
    I fixed it a while ago Aug 18, 2020 at 9:22
  • This looks better than solution with indexes. Jun 9, 2022 at 7:32
  • 2
    This will throw a RangeError when Platform.localeName only returns a language code without the country code, like "en".
    – mrcendre
    Oct 14, 2022 at 7:42
28

Try this:

import 'dart:ui' as ui;
......
 @override
  Widget build(BuildContext context) {
// get system language code
    _sysLng = ui.window.locale.languageCode;    
...
4
  • Returns null always at the start of the app. Jul 1, 2019 at 8:25
  • 5
    Always returns 'en' no matter what. Oct 18, 2019 at 14:19
  • using iOS 13 there seems to be a bug as it returns null ... so I don't find this method reliable. From now on I only use Locale myLocale = Localizations.localeOf(context); Nov 27, 2019 at 13:25
  • Is not system language, is the window language but the system can have other language enabled by default. By example, when start an application with custom locale enviroment.
    – e-info128
    Sep 25, 2022 at 1:18
23

If you write Platform.localeName, it gives you language and country like "en_US", "tr_TR".

To take just "en" or "tr", you can use substring() and take first 2 letter.

String deviceLanguage= Platform.localeName.substring(0,2);

It gives to you only "en" or "tr" etc...

If you want the country codes, use this;

String deviceCountry= Platform.localeName.substring(3,5);

It gives to you only "US" or "TR" etc...

7

The steps to make it work are:

  1. Add the package as a dependency to your pubspec.yaml file

    dependencies:
       flutter:
       sdk: flutter
    flutter_localizations:
       sdk: flutter
    
  2. Import the flutter_localizations library and specify localizationsDelegates and supportedLocales for MaterialApp

    import 'package:flutter_localizations/flutter_localizations.dart';
    
    MaterialApp(
    localizationsDelegates: [
        // ... app-specific localization delegate[s] here
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
    ],
    
    supportedLocales: [
        const Locale('en', ''), // English, no country code
        const Locale('es', ''), // Spanish, no country code
        // ... other locales the app supports
     ],
    // ...
    )
    
  3. For iOS only: open the ios module and add the supported languages under localization

enter image description here

  1. Get the current locale

    Locale myLocale = Localizations.localeOf(context);

You can access the countryCode and languageCode strings properties fo Locale if needed enter image description here

3

For timezone, all other answers will give abbreviations like 'CET', 'MSK' etc. and GMT offset.

To get the device's timezone in format of Europe/Paris, use flutter_native_timezone package:

final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
2

When using the easy_localization plugin on a project, the current code will greatly simplify obtaining the system language of the device. Since the plugin has an extension for localeName

import 'package:easy_localization/easy_localization.dart';

Platform.localeName.toLocale().languageCode
Platform.localeName.toLocale().countryCode

To get a timezone, there is already a good answer from @Günter Zöchbauer with a link to the documentation

3
  • Thank you for editing. Is it possible to get the timezone from this library? If so, can you include that, since it was asked for in the question? Jul 25 at 17:10
  • 1
    Unfortunately, there is no such thing in this library. According to the time zone, many answers were higher. I just suggested one of the easiest ways to get the system language and country if this library is used on the project Jul 26 at 8:49
  • That makes sense, and is useful information. Could you edit your answer to make a note of that? It may also be useful to link to one of the other answers as a “signpost” for answering the timezone part of the question Jul 26 at 17:49
2

To extend on Alexander Pravdin's answer:

System Locales

import 'package:flutter/material.dart';
// or import 'package:flutter/widgets.dart';
final List<Locale> systemLocales =
    WidgetsBinding.instance.platformDispatcher.locales;
print(systemLocales);

For example, this would return list of Preferred languages from chrome://settings/languages

Locale used by Application

import 'package:flutter/material.dart';
// or import 'package:flutter/widgets.dart';
final Locale appLocale = Localizations.localeOf(context);
print(appLocale);

Documentation Links:

  1. PlatformDispatcher.locales
  2. Localizations.localeOf()
0

My suggestion:

import 'dart:io';
        
String getDeviceLanguage(){
  return Platform.localeName.contains("_")
      ? Platform.localeName.split("_")[0]
      : Platform.localeName;
}

There are some solution in this page like following but these codes won't work for (Filipino Pilipino - fil) and (Finnish - fi) and gives same result.

String deviceLanguage= Platform.localeName.substring(0,2);

Because according to documentation of Flutter:

The result usually consists of

a language (e.g., "en"), or a language and country code (e.g. "en_US", "de_AT"), or a language, country code and character set (e.g. "en_US.UTF-8").

Source: https://api.flutter.dev/flutter/dart-io/Platform/localeName.html

Source: https://api.flutter.dev/flutter/flutter_localizations/GlobalMaterialLocalizations-class.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.