jsonDecodeNullableMap function
Decodes a JSON string into a non-empty Map<String, dynamic> or null.
Returns null if the input is empty or decodes to an empty map.
final result = jsonDecodeNullableMap('{"key": "value"}');
print(result); // {key: value}
final emptyResult = jsonDecodeNullableMap('{}');
print(emptyResult); // null
@ai Use when you need to distinguish between empty and non-empty maps. Handle errors externally.
Implementation
Map<String, dynamic>? jsonDecodeNullableMap(final dynamic json) {
if (json case final Map<String, dynamic> map) return map.isEmpty ? null : map;
final jsonString = jsonDecodeString(json);
if (jsonString.isEmpty) return null;
return switch (jsonDecode(jsonString)) {
final Map<String, dynamic> map => map.isEmpty ? null : map,
_ => null,
};
}