Setting local happens using Locale() constructor. It takes language code and country code. Locale is used the change the language on button click or onPressed events.
Flutter framework recognizes different language using language code and country code. If you have many languages, then you should save those languages and related info in List. In the list you should save the language related info by creating a object using model.
Those language objects must contain country code and language code. Make sure they are save in List.
After that you can access a specific language from the List. As you access a specific language you actually access the country code and language code.
As you change the country code and language code, you are changing the locale.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LocalizationController extends GetxController implements GetxService {
final SharedPreferences sharedPreferences;
LocalizationController({@required this.sharedPreferences}) {
loadCurrentLanguage();
}
Locale _locale = Locale(AppConstants.languages[0].languageCode, AppConstants.languages[0].countryCode);
bool _isLtr = true;
List<LanguageModel> _languages = [];
Locale get locale => _locale;
List<LanguageModel> get languages => _languages;
void setLanguage(Locale locale) {
Get.updateLocale(locale);
_locale = locale;
saveLanguage(_locale);
update();
}
void loadCurrentLanguage() async {
_locale = Locale(sharedPreferences.getString(AppConstants.LANGUAGE_CODE) ?? AppConstants.languages[0].languageCode,
sharedPreferences.getString(AppConstants.COUNTRY_CODE) ?? AppConstants.languages[0].countryCode);
_isLtr = _locale.languageCode != 'ar';
for(int index = 0; index<AppConstants.languages.length; index++) {
if(AppConstants.languages[index].languageCode == _locale.languageCode) {
_selectedIndex = index;
break;
}
}
_languages = [];
_languages.addAll(AppConstants.languages);
update();
}
void saveLanguage(Locale locale) async {
sharedPreferences.setString(AppConstants.LANGUAGE_CODE, locale.languageCode);
sharedPreferences.setString(AppConstants.COUNTRY_CODE, locale.countryCode);
}
int _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
void setSelectIndex(int index) {
_selectedIndex = index;
update();
}
void searchLanguage(String query) {
if (query.isEmpty) {
_languages = [];
_languages = AppConstants.languages;
} else {
_selectedIndex = -1;
_languages = [];
AppConstants.languages.forEach((language) async {
if (language.languageName.toLowerCase().contains(query.toLowerCase())) {
_languages.add(language);
}
});
}
update();
}