Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Dynamic language based on device

I´am trying to get the mobile countryCode and languageCode using Localizations

Widget build(BuildContext context) {
        Locale myLocale = Localizations.localeOf(context);
        print(myLocale.countryCode);
        print(myLocale.languageCode);
        return MaterialApp(
          title: 'Title',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,       
          ),
          home: LoginPage(),
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: [
            Locale('es' 'ES'),
          ],
        );
      }

But return "Localizations ancestor was not found".Somebody know what is the correct way to do this?

like image 963
El Hombre Sin Nombre Avatar asked Mar 07 '19 11:03

El Hombre Sin Nombre


People also ask

How do you support multiple languages in Flutter?

By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp ) properties, and include a package called flutter_localizations . As of November 2020, this package supports 78 languages.

How do you add multi language support to your Flutter app via dynamic localization?

You can add any number of language support by adding . arb files, the process for that is very simple. Just click on Tools > Flutter Intl > Add Locale.

How do you change the Flutter app language without restarting the app?

On the MainModel , all you need to do is change the preferredLanguageCode variable to whatever you want ('en', 'ar', 'es', etc). Don't forget to call NotifyListeners() once you change the language.


1 Answers

Use LocaleResolutionCallback to get the device locale :

 Widget build(BuildContext context) {
    Locale myLocale ;

    return MaterialApp(
      title: 'Title',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,       
      ),
      home: LoginPage(),
      localeResolutionCallback: (deviceLocale, supportedLocales) {
      myLocale = deviceLocale ; // here you make your app language similar to device language , but you should check whether the localization is supported by your app
      print(myLocale.countryCode);
      print(myLocale.languageCode);
      }
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('es' 'ES'),
      ],
    );
  }
like image 54
Mazin Ibrahim Avatar answered Dec 25 '22 13:12

Mazin Ibrahim