/* This is the app localizations for multi language This function is used to change the language We used shared preferences to change a whole language of the apps */ import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:mobdr/service/shared_prefs.dart'; class AppLocalizations { final Locale locale; AppLocalizations(this.locale); static AppLocalizations? of(BuildContext context) { return Localizations.of(context, AppLocalizations); } late Map _localizedStrings; Future load() async { // Load the language JSON file from the "lang" folder String jsonString = await rootBundle.loadString('assets/lang/${locale.languageCode}.json'); Map jsonMap = json.decode(jsonString); _localizedStrings = jsonMap.map((key, value) { return MapEntry(key, value.toString()); }); return true; } // This method will be called from every widget which needs a localized text String translate(String key) { final translatedString = _localizedStrings[key]; return translatedString ?? 'I18N:' + key; } } class AppLocalizationsDelegate extends LocalizationsDelegate { const AppLocalizationsDelegate(); @override bool isSupported(Locale locale) { // Include all of your supported language codes here return ['fr', 'en'].contains(locale.languageCode); } @override Future load(Locale locale) async { locale = SharedPrefs().language; AppLocalizations localizations = new AppLocalizations(locale); await localizations.load(); return localizations; } @override bool shouldReload(AppLocalizationsDelegate old) => true; }