notification_settings_provider.dart
1 import 'package:flutter_riverpod/flutter_riverpod.dart'; 2 import 'package:shared_preferences/shared_preferences.dart'; 3 4 const _enabledKey = 'notification_settings_enabled'; 5 const _soundKey = 'notification_settings_sound'; 6 7 class NotificationSettings { 8 final bool enabled; 9 final bool soundEnabled; 10 11 const NotificationSettings({ 12 this.enabled = true, 13 this.soundEnabled = true, 14 }); 15 16 NotificationSettings copyWith({bool? enabled, bool? soundEnabled}) { 17 return NotificationSettings( 18 enabled: enabled ?? this.enabled, 19 soundEnabled: soundEnabled ?? this.soundEnabled, 20 ); 21 } 22 } 23 24 final notificationSettingsProvider = 25 StateNotifierProvider<NotificationSettingsNotifier, NotificationSettings>( 26 (ref) { 27 return NotificationSettingsNotifier(); 28 }); 29 30 class NotificationSettingsNotifier extends StateNotifier<NotificationSettings> { 31 NotificationSettingsNotifier() : super(const NotificationSettings()) { 32 _load(); 33 } 34 35 Future<void> _load() async { 36 final prefs = await SharedPreferences.getInstance(); 37 state = NotificationSettings( 38 enabled: prefs.getBool(_enabledKey) ?? true, 39 soundEnabled: prefs.getBool(_soundKey) ?? true, 40 ); 41 } 42 43 Future<void> setEnabled(bool enabled) async { 44 state = state.copyWith(enabled: enabled); 45 final prefs = await SharedPreferences.getInstance(); 46 await prefs.setBool(_enabledKey, enabled); 47 } 48 49 Future<void> setSoundEnabled(bool soundEnabled) async { 50 state = state.copyWith(soundEnabled: soundEnabled); 51 final prefs = await SharedPreferences.getInstance(); 52 await prefs.setBool(_soundKey, soundEnabled); 53 } 54 }