我的目标是保存ThemeMode首选项,即使在应用程序关闭时。我试着遵循一些指南,但没有成功,我需要知道我做错了什么。
有人能帮我,给我提供正确的代码吗?
provider.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();
}
}
drawer.dart
@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);
},
),
],
),
);
}
这就是我为我的应用程序使用的,它有三个主题,但工作…
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());
}
}