import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; part 'sharedPrefs.g.dart'; final sharedPreferencesProvider = Provider((ref) => throw UnimplementedError()); class SharedPrefNotifier extends StateNotifier { final SharedPreferences prefs; final String key; final T defaultValue; SharedPrefNotifier({ required this.prefs, required this.key, required this.defaultValue, }) : super(prefs.containsKey(key) ? _getValue(prefs, key, defaultValue) : defaultValue); // Helper to get the value with proper typing static T _getValue(SharedPreferences prefs, String key, T defaultValue) { switch (T) { case String: return prefs.getString(key) as T ?? defaultValue; case bool: return prefs.getBool(key) as T ?? defaultValue; case int: return prefs.getInt(key) as T ?? defaultValue; case double: return prefs.getDouble(key) as T ?? defaultValue; case const (List): return prefs.getStringList(key) as T ?? defaultValue; default: throw UnsupportedError('Type $T not supported by SharedPreferences'); } } Future update(T value) async { switch (T) { case String: await prefs.setString(key, value as String); break; case bool: await prefs.setBool(key, value as bool); break; case int: await prefs.setInt(key, value as int); break; case double: await prefs.setDouble(key, value as double); break; case const (List): await prefs.setStringList(key, value as List); break; default: throw UnsupportedError('Type $T not supported by SharedPreferences'); } state = value; } } final isDarkModeProvider = StateNotifierProvider, bool>((ref) { final prefs = ref.watch(sharedPreferencesProvider); return SharedPrefNotifier( prefs: prefs, key: 'is_dark_mode', defaultValue: false, ); });