write method
Encodes and writes an arbitrary JSON value, this is method should only be called when a value is expected.
Implementation
Future<void> write(Object? value) async {
// We put the constant on the lhs of these comparisons so it doesn't invoke
// operator overloads
if (value is String ||
value is num ||
true == value ||
false == value ||
null == value) {
await writeRawBuffer(_encodeValue(value));
} else if (value is List) {
await startList();
for (final element in value) {
await write(element);
}
await end();
} else if (value is Map) {
await startMap();
for (final entry in value.entries) {
Object? key = entry.key;
if (key is! String) {
key = await _reduce(key);
}
if (key is String) {
await writeKey(key);
} else if (key is Stream<String>) {
await writeKeyStream(key);
} else {
throw ArgumentError(
'Invalid map key ${key.runtimeType}, only Strings are '
'allowed in JSON',
);
}
await write(entry.value);
}
await end();
} else if (value is Stream<String>) {
return writeStringStream(value);
} else if (value is Future) {
return write(await value);
} else if (value is Function) {
return write(await value());
} else {
final Object? newValue = await (value as dynamic).toJson();
return write(newValue);
}
}