savedPreferences for themes

This commit is contained in:
2026-03-11 20:28:19 +01:00
parent 4d03756fa2
commit 4156ea4f16
3 changed files with 47 additions and 2 deletions

View File

@@ -1,12 +1,51 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
static const String _themeKey = 'theme_mode';
ThemeMode _themeMode = ThemeMode.system;
ThemeMode get theme => _themeMode;
void setTheme(ThemeMode mode) {
_themeMode = mode;
ThemeProvider() {
_loadTheme();
}
Future<void> _loadTheme() async {
final prefs = await SharedPreferences.getInstance();
final themeName = prefs.getString(_themeKey) ?? 'system';
_themeMode = _themeFromString(themeName);
notifyListeners();
}
Future<void> setTheme(ThemeMode mode) async {
_themeMode = mode;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_themeKey, _themeToString(mode));
}
String _themeToString(ThemeMode mode) {
switch (mode) {
case ThemeMode.light:
return 'light';
case ThemeMode.dark:
return 'dark';
case ThemeMode.system:
return 'system';
}
}
ThemeMode _themeFromString(String theme) {
switch (theme) {
case 'light':
return ThemeMode.light;
case 'dark':
return ThemeMode.dark;
case 'system':
default:
return ThemeMode.system;
}
}
}