73 lines
1.9 KiB
Dart
73 lines
1.9 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Manages app locale with persistence
|
|
class LocaleProvider extends ChangeNotifier {
|
|
static const String _localeKey = 'app_locale';
|
|
|
|
Locale _locale = const Locale('en');
|
|
|
|
Locale get locale => _locale;
|
|
|
|
/// Supported locales
|
|
static const List<Locale> supportedLocales = [
|
|
Locale('en'), // English
|
|
Locale('nl'), // Dutch
|
|
Locale('ru'), // Russian
|
|
];
|
|
|
|
/// Locale display names
|
|
static const Map<String, String> localeNames = {
|
|
'en': 'English',
|
|
'nl': 'Nederlands',
|
|
'ru': 'Русский',
|
|
};
|
|
|
|
/// Short codes for display in header
|
|
static const Map<String, String> localeCodes = {
|
|
'en': 'EN',
|
|
'nl': 'NL',
|
|
'ru': 'RU',
|
|
};
|
|
|
|
LocaleProvider() {
|
|
_loadLocale();
|
|
}
|
|
|
|
/// Load saved locale from preferences
|
|
Future<void> _loadLocale() async {
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final localeCode = prefs.getString(_localeKey);
|
|
if (localeCode != null && supportedLocales.any((l) => l.languageCode == localeCode)) {
|
|
_locale = Locale(localeCode);
|
|
notifyListeners();
|
|
}
|
|
} catch (e) {
|
|
// Fallback to default if loading fails
|
|
debugPrint('Failed to load locale: $e');
|
|
}
|
|
}
|
|
|
|
/// Set and persist locale
|
|
Future<void> setLocale(Locale locale) async {
|
|
if (!supportedLocales.contains(locale)) return;
|
|
|
|
_locale = locale;
|
|
notifyListeners();
|
|
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString(_localeKey, locale.languageCode);
|
|
} catch (e) {
|
|
debugPrint('Failed to save locale: $e');
|
|
}
|
|
}
|
|
|
|
/// Get current locale name for display
|
|
String get currentLocaleName => localeNames[_locale.languageCode] ?? 'English';
|
|
|
|
/// Get current locale code for header display
|
|
String get currentLocaleCode => localeCodes[_locale.languageCode] ?? 'EN';
|
|
}
|