Reviewed-on: #2 Co-authored-by: Felipe M. <me@fmartingr.com> Co-committed-by: Felipe M. <me@fmartingr.com>
48 lines
1.4 KiB
Dart
48 lines
1.4 KiB
Dart
import 'dart:ui';
|
|
|
|
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
part 'locale_provider.g.dart';
|
|
|
|
/// Key for storing locale preference in SharedPreferences
|
|
const String _localeKey = 'app_locale';
|
|
|
|
/// Provider for locale state management
|
|
/// State is Locale? where null means "use system default"
|
|
@riverpod
|
|
class LocaleNotifier extends _$LocaleNotifier {
|
|
@override
|
|
Locale? build() {
|
|
_loadLocale();
|
|
return null; // Default: system locale
|
|
}
|
|
|
|
/// Load locale from SharedPreferences
|
|
Future<void> _loadLocale() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final localeString = prefs.getString(_localeKey);
|
|
|
|
if (localeString != null) {
|
|
final parts = localeString.split('_');
|
|
final locale =
|
|
parts.length > 1 ? Locale(parts[0], parts[1]) : Locale(parts[0]);
|
|
state = locale;
|
|
}
|
|
}
|
|
|
|
/// Set locale and persist to SharedPreferences
|
|
/// Pass null to use system default
|
|
Future<void> setLocale(Locale? locale) async {
|
|
state = locale;
|
|
final prefs = await SharedPreferences.getInstance();
|
|
if (locale == null) {
|
|
await prefs.remove(_localeKey);
|
|
} else {
|
|
final localeString = locale.countryCode != null
|
|
? '${locale.languageCode}_${locale.countryCode}'
|
|
: locale.languageCode;
|
|
await prefs.setString(_localeKey, localeString);
|
|
}
|
|
}
|
|
}
|