If you have multiple language support in your app, you need to work with locale. Locale could be confusing for beginners.
An identifier used to select a user’s language and formatting preferences. It means you can save user’s language code and country code.
In general in app, we set a default language code and country code. This happens when app gets installed first time. This could be changed later.
We set up the default language code and country code by using Locale() class. It takes country code and language code.
Locale _locale = Locale(AppConstants.languages[0].languageCode,
AppConstants.languages[0].countryCode)
To be able to set it, it’s better you format the in a separate file
static List<LanguageModel> languages = [
LanguageModel(imageUrl: "xx", languageName: 'English', countryCode: 'US', languageCode: 'en'),
LanguageModel(imageUrl: "xx", languageName: 'বাংলা', countryCode: 'BD', languageCode: 'bn'),
];
See how we set the language code and country code. This is the exact information that we read from Locale() constructor.
In general you would save your language information in json files. Each time you change the language, you should change the locale as well.
After changing the locale, you should save the country code and language code in sharedPreference.
If you change the language setting from UI, you must change it through Locale.
If you use Getx, you need to use
Get.updateLocale(locale);
The above line should be called before you set the local to Local object in your controller.
So the most basic idea about locale
- it saves country code and language code
- reading and saving language code and country code should happen through Locale()
App with locale example