I have just booleans which i need to save in local storage so I am using Sharedpreferences. But issue is values is saving in local storage also its getting it from local storage but when I call my provider in an widget its not showing local storage value look like its creating or showing as an seperate instance.
My code
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
class notificationState {
final bool music_bool;
final bool sound_bool;
final bool vibratio_bool;
notificationState({
this.music_bool = false,
this.sound_bool = false,
this.vibratio_bool = false,
});
// You can add a method to copy the current state with modified fields.
notificationState copyWith({
bool? music_bool,
bool? sound_bool,
bool? vibratio_bool,
}) {
return notificationState(
vibratio_bool: vibratio_bool ?? this.vibratio_bool,
music_bool: music_bool ?? this.music_bool,
sound_bool: sound_bool ?? this.sound_bool,
);
}
}
class NotificationNotifier extends StateNotifier<notificationState> {
NotificationNotifier() : super(notificationState());
Future<void> loadStateFromPrefs() async {
final prefs = await SharedPreferences.getInstance();
final musicBool = prefs.getBool('music_bool') ?? false;
final soundBool = prefs.getBool('sound_bool') ?? false;
final vibrationBool = prefs.getBool('vibration_bool') ?? false;
print(prefs.getBool('music_bool'));
state = state.copyWith(
music_bool: musicBool,
sound_bool: soundBool,
vibratio_bool: vibrationBool,
);
print(state.music_bool);
}
Future<void> saveStateToPrefs() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('music_bool', state.music_bool);
await prefs.setBool('sound_bool', state.sound_bool);
await prefs.setBool('vibration_bool', state.vibratio_bool);
}
void setSoundBool(bool newValue) {
state = state.copyWith(sound_bool: newValue);
saveStateToPrefs();
}
void setMusicBool(bool newValue) {
state = state.copyWith(music_bool: newValue);
saveStateToPrefs();
}
void setVibrationBool(bool newValue) {
state = state.copyWith(vibratio_bool: newValue);
saveStateToPrefs();
}
}
final notificationProvider =
StateNotifierProvider<NotificationNotifier, notificationState>((ref) {
return NotificationNotifier();
});
I try to print values of loadStatefrompref function and its fine but on widget when I call with provider its showing not that value