Files
zhinian_manage/lib/providers/settings_provider.dart
2026-05-15 14:41:37 +08:00

94 lines
2.7 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/storage_service.dart';
enum AppThemeMode { light, dark, system }
class SettingsState {
final bool pushNotification;
final bool soundNotification;
final AppThemeMode themeMode;
final Locale locale;
const SettingsState({
this.pushNotification = true,
this.soundNotification = true,
this.themeMode = AppThemeMode.light,
this.locale = const Locale('zh', 'CN'),
});
SettingsState copyWith({
bool? pushNotification,
bool? soundNotification,
AppThemeMode? themeMode,
Locale? locale,
}) {
return SettingsState(
pushNotification: pushNotification ?? this.pushNotification,
soundNotification: soundNotification ?? this.soundNotification,
themeMode: themeMode ?? this.themeMode,
locale: locale ?? this.locale,
);
}
ThemeMode get flutterThemeMode {
switch (themeMode) {
case AppThemeMode.light:
return ThemeMode.light;
case AppThemeMode.dark:
return ThemeMode.dark;
case AppThemeMode.system:
return ThemeMode.system;
}
}
}
class SettingsNotifier extends StateNotifier<SettingsState> {
SettingsNotifier() : super(const SettingsState()) {
_loadSettings();
}
Future<void> _loadSettings() async {
await storageService.init();
final push = storageService.getBool('push_notification');
final sound = storageService.getBool('sound_notification');
final theme = storageService.getString('theme_mode');
final lang = storageService.getString('locale');
state = state.copyWith(
pushNotification: push ?? true,
soundNotification: sound ?? true,
themeMode: theme != null
? AppThemeMode.values.byName(theme)
: AppThemeMode.light,
locale: lang != null
? Locale(lang.split('_')[0], lang.split('_')[1])
: const Locale('zh', 'CN'),
);
}
Future<void> setPushNotification(bool value) async {
await storageService.setBool('push_notification', value);
state = state.copyWith(pushNotification: value);
}
Future<void> setSoundNotification(bool value) async {
await storageService.setBool('sound_notification', value);
state = state.copyWith(soundNotification: value);
}
Future<void> setThemeMode(AppThemeMode mode) async {
await storageService.setString('theme_mode', mode.name);
state = state.copyWith(themeMode: mode);
}
Future<void> setLocale(Locale locale) async {
await storageService.setString('locale', '${locale.languageCode}_${locale.countryCode}');
state = state.copyWith(locale: locale);
}
}
final settingsProvider = StateNotifierProvider<SettingsNotifier, SettingsState>((ref) {
return SettingsNotifier();
});