Created
June 27, 2023 13:50
-
-
Save RobertApikyan/e15b52ac48d6d80667b328d080f68ed7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:get/get.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
/// This class allows to change app locale | |
class AppLocaleHelper { | |
static const en = 'en'; | |
static const de = 'de'; | |
static const enLocale = Locale(en); | |
static const deLocale = Locale(de); | |
static const _languageCode = 'languageCode'; | |
static String? lastSelectedCode; | |
static Future<void> updateLocale(Locale locale, BuildContext context) async { | |
var prefs = await SharedPreferences.getInstance(); | |
lastSelectedCode = locale.languageCode; | |
await prefs.setString(_languageCode, locale.languageCode); | |
unawaited(Get.updateLocale(locale)); | |
} | |
/// Returns last selected language code, if there is not selected language | |
/// code it returns default language code (see [fetchDefaultLanguageCode]). | |
static Future<String?> fetchLanguageCode() async { | |
if (lastSelectedCode != null) { | |
return lastSelectedCode; | |
} | |
var prefs = await SharedPreferences.getInstance(); | |
lastSelectedCode = prefs.getString(_languageCode) ?? await fetchDefaultLanguageCode(); | |
return lastSelectedCode; | |
} | |
/// Returns language code based on device locale. | |
static Future<String> fetchDefaultLanguageCode() async { | |
final locale = Platform.localeName; | |
if(locale.toLowerCase().contains(de)){ | |
return de; | |
}else{ | |
return en; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment