createPrefProvider<T> function
- required String prefKey,
- required T defaultValue,
Returns the Provider
that has access to the value of preferences.
Persist the value of the type parameter T type in SharedPreferences.
The argument prefs
specifies an instance of SharedPreferences.
The arguments prefKey
and defaultValue
specify the key name and default
value of the preference.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final booPrefProvider = createPrefProvider<bool>(
prefs: (_) => prefs,
prefKey: "boolValue",
defaultValue: false,
);
When referring to a value, use it as you would a regular provider.
Consumer(builder: (context, watch, _) {
final value = watch(booPrefProvider);
To change the value, use the update() method.
await watch(booPrefProvider.notifier).update(true);
Implementation
StateNotifierProvider<PrefNotifier<T>, T> createPrefProvider<T>({
required String prefKey,
required T defaultValue,
}) {
return StateNotifierProvider<PrefNotifier<T>, T>((ref) {
final clientId =
ref.watch(alwaysClientProvider.select((v) => v.deviceId().toString()));
return PrefNotifier<T>('$clientId-$prefKey', defaultValue);
});
}