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

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom3652