Requested the Locale of a context that does not include a Localizations ancestor

Viewed 1127

I am trying to get the Locale of the user's phone at app start.

I have this Widget tree in the runApp() method :

@override
  Widget build(BuildContext context) {
    return MaterialApp(
            locale: Locale(Localizations.localeOf(context).languageCode), // This crashes
            localizationsDelegates: [
              const LocalizationDelegate(), // My custom delegate to get translations
              CountryLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
            supportedLocales: [
              Locale("en"),
              Locale("fr"),
            ],
            debugShowCheckedModeBanner: false,
            home: Scaffold(
              resizeToAvoidBottomInset: false,
              body: HomePage(),
            )
        );
}

the line locale: Locale(Localizations.localeOf(context).languageCode) cause a crash with :

Requested the Locale of a context that does not include a Localizations ancestor.

I simply want to bind this locale to my Delegate without going further in app.
So far, i put locale: Locale("en") to read my en.json file from my LocalizationDelegate.

2 Answers

You have to use a MaterialApp or CupertinoApp to use Locales.

For ex,

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: const <Locale>[
        Locale('de'),
        Locale('en'),
        Locale('es')
      ],
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const YourHomeWidget(), // All Localized Widgets must be placed inside home widget.
    );
  }
}

NOTE: Flutter Localization automatically detect system language and apply this settings to your application.

I also answer because @Jaydipsinh is right but the error i was making is that i thought i needed this line :

locale: Locale(Localizations.localeOf(context).languageCode)

Whereas it's useless.
You simply have to put supportedLocales values and if they match the phone's locale, flutter automatically use the langage for the given delegates, for example :

GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate

Also, you can retrieve the locale by using : String locale = Platform.localeName.split('_')[0]; with no crash at app start.

Related