flutterlocalesetlocale

Flutter: How can I get list of device locales before building starts?


I want to internationalize my application. To ease translations, I want to use i18n_extension package.

I need to get the list of device locales (any device, even web) before any widget building process starts.

This is required to initially set the correct locale (which can be taken from a server) both for I18n and for Localizations (in WidgetsApp).

The only way I found to get the list of device locales is:

MaterialApp(
  localeListResolutionCallback: (deviceLocales, appLocales) => myLocaleResolution(deviceLocales, appLocales),
  locale: thisAppsLocale,
  home: I18n(
    child: MyHomePage(),
    initialLocale: thisAppsLocale, ),

Method myLocaleResolution sets thisAppsLocale. Method is invoked once at startup and when the user changes the device locale. So thisAppsLocale is only available after the first build process and cannot be used to set locale and initialLocale. Using setState() within myLocaleResolution throws an exception on startup invocation.


Solution

  • Use window.locales:

    import 'dart:ui';
    import 'package:flutter/material.dart';
    
    void main(){
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          locale: window.locale,
          supportedLocales: window.locales,
          home: Scaffold(),
        );
      }
    }
    
    

    The window singleton gives you access to the Window class.