removeNull static method

dynamic removeNull(
  1. dynamic input,
  2. [bool removeEmptyCollections = true]
)

Removes null values from the given input. This defaults to removing empty lists and maps. To override this default, set the optional removeEmptyCollections to false.

For example, if the the starting input is:

{
  "foo": "bar",
  "other": null,
  "map": {
    "value": null
  }
}

A call to removeNull will result in the final string:

{
  "foo": "bar"
}

Implementation

static dynamic removeNull(
  dynamic input, [
  bool removeEmptyCollections = true,
]) {
  dynamic result;

  if (input != null) {
    result ??= <String, dynamic>{};

    for (var entry in input.entries) {
      if (entry.value != null) {
        if (entry.value is Map) {
          final processed = removeNull(
            entry.value,
            removeEmptyCollections,
          );
          if (processed != null) {
            result[entry.key] = processed;
          }
        } else if (removeEmptyCollections != true ||
            entry.value is! List ||
            entry.value?.isNotEmpty == true) {
          result[entry.key] = entry.value;
        }
      }
    }
  }

  return result?.isNotEmpty == true || removeEmptyCollections == false
      ? result
      : null;
}