PrfJson<T> constructor

PrfJson<T>(
  1. String key, {
  2. required T fromJson(
    1. Map<String, dynamic> json
    ),
  3. required Map<String, dynamic> toJson(
    1. T object
    ),
  4. T? defaultValue,
})

Creates a new JSON preference variable with the specified key.

fromJson is a required function that converts a JSON map to your object type. toJson is a required function that converts your object to a JSON map.

The optional defaultValue is returned if the preference is not found or if an error occurs while reading.

Implementation

PrfJson(
  super.key, {
  required T Function(Map<String, dynamic> json) fromJson,
  required Map<String, dynamic> Function(T object) toJson,
  super.defaultValue,
}) : super(
        from: (jsonString) {
          if (jsonString == null) return null;
          try {
            final map = jsonDecode(jsonString);
            if (map is Map<String, dynamic>) {
              return fromJson(map);
            }
            return null;
          } catch (_) {
            return null;
          }
        },
        to: (obj) => jsonEncode(toJson(obj)),
        getter: (prefs, key) async => prefs.getString(key),
        setter: (prefs, key, value) async =>
            await prefs.setString(key, value),
      );