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?
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.
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.
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.
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'),
],
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With