mi objetivo es guardar la preferencia ThemeMode incluso cuando la aplicación está cerrada. Traté de seguir algunas guías pero sin éxito, necesito saber qué estoy haciendo mal.
¿Puede alguien ayudarme y proporcionarme el código correcto?
proveedor.dart
class ThemeProvider extends ChangeNotifier {
ThemeMode themeMode = ThemeMode.light;
bool get isDarkMode => themeMode == ThemeMode.dark;
void toggleTheme(bool isOn) {
themeMode = isOn? ThemeMode.dark: ThemeMode.light;
notifyListeners();
}
}
cajón.dardo
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeProvider>(context);
return Drawer(
child: ListView(
physics: const ScrollPhysics(),
padding: EdgeInsets.zero,
children: <Widget>[
SwitchListTile(
secondary: Icon(
themeProvider.isDarkMode? Icons.dark_mode: Icons.light_mode,
),
title: const Text('Tema'),
value: themeProvider.isDarkMode,
onChanged: (value) {
final provider =
Provider.of<ThemeProvider>(context, listen: false);
provider.toggleTheme(value);
},
),
],
),
);
}
Solución del problema
Esto es lo que uso para mi aplicación, tiene tres temas pero funciona...
ThemeNotifier(IAppRepository appRepository) {
_appPrefsUseCase = AppPrefsUseCase(appRepository);
_loadFromPrefs();
}
toggleTheme(int index) {
var type = ThemeType.values[index];
_saveToPrefs(type);
notifyListeners();
}
void _loadFromPrefs() async {
final _theme = _appPrefsUseCase?.call<String>(AppKeys.theme);
_userTheme = ThemeType.values
.firstWhere((t) => t.toString() == _theme, orElse: () => _userTheme);
notifyListeners();
}
void _saveToPrefs(ThemeType type) {
_userTheme = type;
_appPrefsUseCase?.savePref(key: AppKeys.theme, value: type.toString());
}
}
No hay comentarios:
Publicar un comentario