Files
sxchnge/frontend/app/lib/providers/locale.dart
T
Stephan D 10a278c65a Deliver localized auth app with verification and go_router
Integrate themed login/signup, EN/RU localization, shared dummy providers, verification recovery screens and named URL routes. Store frontend guidelines, workflow skills, validation and delivery documentation. Related to #2, #3, #5 and #6.
2026-09-11 15:37:07 +02:00

51 lines
1.6 KiB
Dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LocaleProvider extends ChangeNotifier {
static const storageKey = 'sxchnge_last_locale';
LocaleProvider({Locale initialLocale = const Locale('en'), this.preferences})
: _locale = resolve(initialLocale.languageCode, const []);
Locale _locale;
final SharedPreferences? preferences;
Future<bool> _pendingSave = Future.value(true);
Locale get locale => _locale;
static Locale resolve(String? saved, List<Locale> systemLocales) {
final code =
saved?.split(RegExp('[-_]')).first ??
(systemLocales.isEmpty ? 'en' : systemLocales.first.languageCode);
return Locale(code == 'ru' ? 'ru' : 'en');
}
static Future<LocaleProvider> load(List<Locale> systemLocales) async {
try {
final prefs = await SharedPreferences.getInstance();
return LocaleProvider(
initialLocale: resolve(prefs.getString(storageKey), systemLocales),
preferences: prefs,
);
} catch (_) {
return LocaleProvider(initialLocale: resolve(null, systemLocales));
}
}
Future<bool> setLocale(Locale value) {
final next = resolve(value.languageCode, const []);
if (next == _locale) return _pendingSave;
_locale = next;
notifyListeners();
// Serialize writes so rapid language changes persist the last selection.
_pendingSave = _pendingSave.then((_) async {
try {
return await preferences?.setString(storageKey, next.languageCode) ??
false;
} catch (_) {
return false;
}
});
return _pendingSave;
}
}