read method Null safety

void read(
  1. Map<String, dynamic> object,
  2. {Iterable<String>? accept,
  3. Iterable<String>? ignore,
  4. Iterable<String>? reject,
  5. Iterable<String>? require}
)

Reads values from object, after applying filters.

The key name must exactly match the name of the property as defined in the receiver's type. If object contains a key that is unknown to the receiver, an exception is thrown (status code: 400).

accept, ignore, reject and require are filters on object's keys with the following behaviors:

If accept is set, all values for the keys that are not given are ignored and discarded. If ignore is set, all values for the given keys are ignored and discarded. If reject is set, if object contains any of these keys, a status code 400 exception is thrown. If require is set, all keys must be present in object.

Usage: var values = json.decode(await request.body.decode()); var user = User() ..read(values, ignore: "id");

Implementation

void read(
  Map<String, dynamic> object, {
  Iterable<String>? accept,
  Iterable<String>? ignore,
  Iterable<String>? reject,
  Iterable<String>? require,
}) {
  if (accept == null && ignore == null && reject == null && require == null) {
    readFromMap(object);
    return;
  }

  final copy = Map<String, dynamic>.from(object);
  final stillRequired = require?.toList();
  for (final key in object.keys) {
    if (reject?.contains(key) ?? false) {
      throw SerializableException(["invalid input key '$key'"]);
    }
    if ((ignore?.contains(key) ?? false) ||
        !(accept?.contains(key) ?? true)) {
      copy.remove(key);
    }
    stillRequired?.remove(key);
  }

  if (stillRequired?.isNotEmpty ?? false) {
    throw SerializableException(
      ["missing required input key(s): '${stillRequired!.join(", ")}'"],
    );
  }

  readFromMap(copy);
}