createMapPrefProvider<T> function

StateNotifierProvider<MapPrefNotifier<T>, T> createMapPrefProvider<T>({
  1. required SharedPreferences prefs(
    1. Ref<Object?>
    ),
  2. required String prefKey,
  3. required T mapFrom(
    1. String?
    ),
  4. required String mapTo(
    1. T
    ),
})

Returns a Provider that can access the preference with any type you want.

Persist to SharePreferences after converting to String. The argument prefs specifies an instance of SharedPreferences. The arguments prefKey and defaultValue specify the key name and default value of the preference. Specify how to convert from String to type T in mapFrom. Specifies how to convert from type T to String in mapTo.


enum EnumValues {
  foo,
  bar,
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final prefs = await SharedPreferences.getInstance();

  final enumPrefProvider = createMapPrefProvider<EnumValues>(
    prefs: (_) => prefs,
    prefKey: "enumValue",
    mapFrom: (v) => EnumValues.values
        .firstWhere((e) => e.toString() == v, orElse: () => EnumValues.foo),
    mapTo: (v) => v.toString(),
  );

When referring to a value, use it as you would a regular provider.


  Consumer(builder: (context, watch, _) {
    final value = watch(enumPrefProvider);

To change the value, use the update() method.


  await watch(enumPrefProvider.notifier).update(EnumValues.bar);

Implementation

StateNotifierProvider<MapPrefNotifier<T>, T> createMapPrefProvider<T>({
  required SharedPreferences Function(Ref) prefs,
  required String prefKey,
  required T Function(String?) mapFrom,
  required String Function(T) mapTo,
}) {
  return StateNotifierProvider<MapPrefNotifier<T>, T>(
      (ref) => MapPrefNotifier<T>(prefs(ref), prefKey, mapFrom, mapTo));
}