set method

void set(
  1. String key,
  2. dynamic value
)

Sets a persistent record given a key and value.

If a default value is available for the given key, checks that the value type and the default type are the same, and throws an exception otherwise. This ensures that any key will always correspond to the same type, as specified in defaultValues.

Implementation

void set(String key, dynamic value) {
  final contextKey = '$prefix:$key';
  // Check if the value has an acceptable type
  if (!(value is String ||
      value is int ||
      value is double ||
      value is bool ||
      value == null)) {
    throw Exception("Invalid value type '${value.runtimeType}'. "
        "Only 'String', 'int', 'double' and 'bool' are allowed, "
        "or 'Null' to unset.");
  }

  // Check type consistency with defaults
  if (defaultValues.containsKey(contextKey) &&
      defaultValues[contextKey].runtimeType != value.runtimeType) {
    throw Exception("The shared preferences value '$contextKey' "
        "cannot be set to a value of type '{$value.runtimeType}', "
        "as its default value has type "
        "'${defaultValues[contextKey].runtimeType}'.");
  }

  // Update value notifier
  final newValue = Map<String, dynamic>.from(notifier!.value);
  newValue[contextKey] = value;
  notifier!.value = newValue;
}