How can I use a localized string from GlobalMaterialLocalizations? - flutter

I want to use one of the predefined localized strings available in the GlobalMaterialLocalizations class. I have added the necessary bits and pieces to my MaterialApp
MaterialApp(
localizationsDelegates: [
const LocalizationDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''),
const Locale('sv', ''),
],
localeResolutionCallback:(Locale locale, Iterable<Locale> supportedLocales) {
return locale; // Return a different locale if the user choose another language in the settings
},
...
and my custom LocalizationDelegate is working fine. I just can't figure out how to use the predefined strings in GlobalMaterialLocalizations, since there is no GlobalMaterialLocalizations.of(BuildContext) method?

Turns out I was looking for the .of(BuildContext) method in the wrong class. To actually use the strings, the MaterialLocalizations class should be used.
Text( MaterialLocalizations.of(context).okButtonLabel )
Hope it might help someone else struggling with the same problem.

Related

How to you change the locale of a flutter app while running?

I'm using
import 'package:flutter_localizations/flutter_localizations.dart'; //For Cupertino stuff
import 'package:localization/localization.dart'; //For actual translations
import 'package:intl/intl.dart'; //For locales
to localize my flutter app. It comes up in the language the phone is set to, but I'd like to add a way to change the language within th e app...I tried using LocalJsonLocalization.delegate.load(locale(lang)) from a button (for now; I'd like to use a dropdown list box but that doesn't seem to be null safe yet), but that didn't actually make the change (I saw the debug log and it said it couldn't load the json language file)...
Try wrapping your MaterialApp in a BlocBuilder.
return BlocBuilder<MainBloc, MainState>(
builder: (context, mainState) {
return MaterialApp(
title: 'MyApp',
locale: mainState.locale,
supportedLocales: L10n.all,
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
);
Then from your button just call the Bloc Event that will change the state of the locale.
Do not forget to add:
WidgetsFlutterBinding.ensureInitialized();
at the beginning of main() function
It should also work fine using Provider.

flutter app does not load local device language

I implemented the Easy localization package on my app, and it works fine when i use the app radio button switch between the different languages. But the aim it is not to let users change language, it is to load local device language and set the app with the local language.
I have changed device language in device settings, but when i re-open the app, language does not change.
Here the main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
runApp(
EasyLocalization(
supportedLocales: [
Locale('en', 'US'),
Locale('it', 'IT'),
Locale('fr', 'FR')
],
path: 'assets/translations',
// <-- change the path of the translation files
fallbackLocale: Locale('en', 'US'),
//assetLoader: CodegenLoader(),
child: MyLangApp(),
),
);
}
Here the MyLangApp:
class MyLangApp extends StatefulWidget {
const MyLangApp({Key? key}) : super(key: key);
#override
State<MyLangApp> createState() => _MyLangAppState();
}
class _MyLangAppState extends State<MyLangApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home: MainPage(),
);
}
}
If you want to get the devices locale use this:
import 'dart:io';
final String defaultLocale = Platform.localeName;
see easy_localization documentation (https://pub.dev/packages/easy_localization) for changing the language:
Found this in the Flutter documentation(https://docs.flutter.dev/development/accessibility-and-localization/internationalization):
Advanced locale definition
Some languages with multiple variants require more than just a language code to properly differentiate.
For example, fully differentiating all variants of Chinese requires specifying the language code, script code, and country code. This is due to the existence of simplified and traditional script, as well as regional differences in the way characters are written within the same script type.
In order to fully express every variant of Chinese for the country codes CN, TW, and HK, the list of supported locales should include:
supportedLocales: [
Locale.fromSubtags(languageCode: 'zh'), // generic Chinese 'zh'
Locale.fromSubtags(
languageCode: 'zh',
scriptCode: 'Hans'), // generic simplified Chinese 'zh_Hans'
Locale.fromSubtags(
languageCode: 'zh',
scriptCode: 'Hant'), // generic traditional Chinese 'zh_Hant'
Locale.fromSubtags(
languageCode: 'zh',
scriptCode: 'Hans',
countryCode: 'CN'), // 'zh_Hans_CN'
Locale.fromSubtags(
languageCode: 'zh',
scriptCode: 'Hant',
countryCode: 'TW'), // 'zh_Hant_TW'
Locale.fromSubtags(
languageCode: 'zh',
scriptCode: 'Hant',
countryCode: 'HK'), // 'zh_Hant_HK'
],
This explicit full definition ensures that your app can distinguish between and provide the fully nuanced localized content to all combinations of these country codes. If a user’s preferred locale is not specified, then the closest match is used instead, which likely contains differences to what the user expects. Flutter only resolves to locales defined in supportedLocales. Flutter provides scriptCode-differentiated localized content for commonly used languages. See Localizations for information on how the supported locales and the preferred locales are resolved.
Although Chinese is a primary example, other languages like French (fr_FR, fr_CA) should also be fully differentiated for more nuanced localization.
Seems that you have to include them all or split the Platform.localeName into language and region and only use language then...
Update
try this:
final deviceLocale= Locale(Platform.localeName)
await context.setLocale(deviceLocale.split('-')[0]);

how to set english as default language when changing language in settings?

How can I set the default language to English if I changed the language in the settings
in this case, I do not have the first language localized, but the other two are localized
therefore, I will always have a second language by default, but I want only English in any such situations
that is, if my language is not localized, I want it to be English instead
i used https://pub.dev/packages/intl library
There is a locale property inside the material app , your can set it to your default language
locale: _locale,
Locale _locale = const Locale('en', '');
return const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: List.from(AppLocalizations.supportedLocales)..sort((a, b) => b.languageCode == "en" ? 1 : 0),
home: MyHomePage(),
);

Problem in displaying localized labels in Dart

I am not able to set localization in my app.
I am trying to add language settings and associated localization in my app. I am able to get-set the language option. I am using 'intl' plug-in for internationalization. My code looks like below in pretty much all the UI .dart files.
AppTranslations.of(context).accountNumber +
" ${accountDetails.accountNumber}",
The getters is set as :
String get accountNumber => _text("account_number");
String _text(String key) {
return _localisedValues[key] ?? _defaultLocaleValues[key];
}
I've also placed json files containing localized labels in 3 different languages. However, it seems there is some instantiation problem of the locazation plug-in. The code doesn't go the getter line.
Any help would be highly appreciated.
AppTranslations.of(context) is a standard way of accessing the localised labels. You are right about the instantiation. If the program doesn't go to the getter line them it means, there's a problem in somewhere in the initial part of the code. It could be in the main.dart.
Check where you are initialising LocalStorageProvider(). In case it is not initialised then that's the problem. Assuming you are using a MaterialApp, try the below suggestion then :
Wrap the MaterialApp with LocalStorageProvider(). I mean, in the main widget build, return LocalStorageProvider() and pass your existing code of MaterialApp() as a child to it. Sample below (Please ignore the theme etc since I just copied the code from one of my app) :
#override
Widget build(BuildContext context) {
LocalStorage localStorage = LocalStorage();
return LocalStorageProvider(
localStorage: localStorage,
child: LocaleProvider(
localStorage: localStorage,
localeWrapper: LocaleWrapper(),
child: Builder(
builder: (context) {
return AnimatedBuilder(
animation: LocaleProvider.of(context).localeWrapper,
builder: (context, _) {
return MaterialApp(
onGenerateTitle: (context) =>
AppTranslations.of(context).appName,
locale: LocaleProvider.of(context).locale,
title: "App Title",
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MapsDemo(),
localizationsDelegates: [
AppTranslationsDelegate(
LocaleProvider.of(context).supportedLanguagesCodes,
),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: LocaleProvider.of(context).supportedLocales,
);
},
);
},
),
),
);
}

Flutter CupertinoDatePicker - can I swap month and day positions?

I need to use CupertinoDatePicker, however its date formatting is mm-dd-yyyy, which in fact is not common for a specific location, where my app will be distributed. I would like to change the format to dd-mm-yyyy, which IMO seems more general.
Is that possible, using that picker?
EDIT: It should be possible in Flutter version 1.7
According to the CupertinoDatePicker documentation:
the class will display its children as
consecutive columns. Its children order is based on
internationalization.
You can read more about internationalization Flutter apps here.
You need to add this to your pubspec.yaml file:
dependencies:
flutter_localizations:
sdk: flutter
And then in your root widget add proper localizationsDelegates:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Application',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''),
const Locale('fr', ''),
],
home: Scaffold(
body: Container(),
),
);
}
}
If you'll use in app one of the localizations that supports dd-mm-yyyy format, e.g. UK English, and you'll have this language set on your device, you should see this widget changed accordingly.