import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; class EstadoIdioma extends ChangeNotifier { EstadoIdioma({SharedPreferences? sharedPreferences}) : _sharedPreferences = sharedPreferences { _cargar(); } static const String _keyLocale = 'idioma_manual_v1'; final SharedPreferences? _sharedPreferences; Locale? _localeSeleccionado; Locale? get localeSeleccionado => _localeSeleccionado; bool get usaSistema => _localeSeleccionado == null; Future seleccionarSistema() async { _localeSeleccionado = null; notifyListeners(); final prefs = await _resolverPrefs(); await prefs.remove(_keyLocale); } Future seleccionarLocale(Locale locale) async { final tag = _serializarLocale(locale); _localeSeleccionado = locale; notifyListeners(); final prefs = await _resolverPrefs(); await prefs.setString(_keyLocale, tag); } Future _cargar() async { final prefs = await _resolverPrefs(); final localeGuardado = prefs.getString(_keyLocale); _localeSeleccionado = _parsearLocale(localeGuardado); notifyListeners(); } Future _resolverPrefs() async { return _sharedPreferences ?? SharedPreferences.getInstance(); } Locale? _parsearLocale(String? value) { if (value == null || value.trim().isEmpty) return null; final partes = value.split('_'); final languageCode = partes.first; if (languageCode.isEmpty) return null; final countryCode = partes.length > 1 && partes[1].isNotEmpty ? partes[1] : null; return Locale.fromSubtags( languageCode: languageCode, countryCode: countryCode, ); } String _serializarLocale(Locale locale) { final countryCode = locale.countryCode; if (countryCode == null || countryCode.isEmpty) { return locale.languageCode; } return '${locale.languageCode}_$countryCode'; } }