createPrefProvider<T> function

StateNotifierProvider<PrefNotifier<T>, T> createPrefProvider<T>({
  1. required SharedPreferences prefs(
    1. Ref<Object?>
    ),
  2. required String prefKey,
  3. 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 SharedPreferences Function(Ref) prefs,
  required String prefKey,
  required T defaultValue,
}) {
  return StateNotifierProvider<PrefNotifier<T>, T>(
      (ref) => PrefNotifier<T>(prefs(ref), prefKey, defaultValue));
}