locale_manager.dart 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'dart:ui';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. class LocaleManager {
  4. static const String _localeKey = 'selected_locale';
  5. static const List<Locale> supportedLocales = [
  6. Locale('en', ''), // English
  7. Locale('de', ''), // German
  8. Locale('hu', ''), // Hungarian
  9. ];
  10. static Locale _currentLocale = const Locale('en', '');
  11. static void Function()? _onLocaleChanged;
  12. static Locale get currentLocale => _currentLocale;
  13. /// Set callback for when locale changes
  14. static void setLocaleChangeCallback(void Function() callback) {
  15. _onLocaleChanged = callback;
  16. }
  17. /// Initialize the locale manager and load saved locale
  18. static Future<void> init() async {
  19. final prefs = await SharedPreferences.getInstance();
  20. final savedLocaleCode = prefs.getString(_localeKey);
  21. if (savedLocaleCode != null) {
  22. // Find the saved locale in supported locales
  23. final savedLocale = supportedLocales.firstWhere(
  24. (locale) => locale.languageCode == savedLocaleCode,
  25. orElse: () => _getSystemLocale(),
  26. );
  27. _currentLocale = savedLocale;
  28. } else {
  29. // Use system locale if available, otherwise default to English
  30. _currentLocale = _getSystemLocale();
  31. }
  32. }
  33. /// Get the system locale if supported, otherwise return English
  34. static Locale _getSystemLocale() {
  35. final systemLocale = PlatformDispatcher.instance.locale;
  36. // Check if system locale is supported
  37. for (final supportedLocale in supportedLocales) {
  38. if (supportedLocale.languageCode == systemLocale.languageCode) {
  39. return supportedLocale;
  40. }
  41. }
  42. // Default to English if system locale is not supported
  43. return const Locale('en', '');
  44. }
  45. /// Change the current locale and save it to preferences
  46. static Future<void> setLocale(Locale locale) async {
  47. if (supportedLocales.contains(locale)) {
  48. _currentLocale = locale;
  49. final prefs = await SharedPreferences.getInstance();
  50. await prefs.setString(_localeKey, locale.languageCode);
  51. // Trigger app refresh to apply new locale
  52. _onLocaleChanged?.call();
  53. }
  54. }
  55. /// Get locale display name
  56. static String getLocaleDisplayName(Locale locale) {
  57. switch (locale.languageCode) {
  58. case 'en':
  59. return 'English';
  60. case 'de':
  61. return 'Deutsch';
  62. case 'hu':
  63. return 'Magyar';
  64. default:
  65. return locale.languageCode;
  66. }
  67. }
  68. /// Check if a locale is supported
  69. static bool isLocaleSupported(Locale locale) {
  70. return supportedLocales.any(
  71. (supportedLocale) => supportedLocale.languageCode == locale.languageCode,
  72. );
  73. }
  74. }