encodable static method

Object? encodable(
  1. Object? value, [
  2. int depth = 0
])

Converts value into something jsonEncode accepts.

Models and objects with toJson() are serialized, dates become ISO-8601 strings, and anything else falls back to toString().

Implementation

static Object? encodable(Object? value, [int depth = 0]) {
  if (value == null || value is bool || value is String) return value;
  if (value is num) return value.isFinite ? value : value.toString();
  if (depth > 12) return value.toString();
  if (value is Map) {
    return value.map(
      (dynamic key, dynamic item) =>
          MapEntry(key.toString(), encodable(item, depth + 1)),
    );
  }
  if (value is Iterable) {
    return value.map((dynamic item) => encodable(item, depth + 1)).toList();
  }
  if (value is DateTime) return value.toIso8601String();
  if (value is Duration) return value.inMilliseconds;
  if (value is Enum) return value.name;
  if (value is Model) return encodable(value.toJson(), depth + 1);
  try {
    return encodable((value as dynamic).toJson(), depth + 1);
  } catch (_) {
    return value.toString();
  }
}