toMapStringDynamic static method
Converts dynamic to Map<String, dynamic>.
All keys are converted to String via toString. If the source map
contains keys that produce the same string (e.g. 1 and '1' both
become '1'), the last value wins by default — data is silently
dropped. Pass ensureUniqueKey: true to keep the first value instead
(uses Map.putIfAbsent).
Args: json: The value to convert. ensureUniqueKey: If true, uses putIfAbsent to keep first value on duplicate string keys. Defaults to false (last value wins).
Implementation
static Map<String, dynamic>? toMapStringDynamic(
dynamic json, {
bool ensureUniqueKey = false,
}) {
if (json == null) return null;
if (json is Map<String, dynamic>) return json;
if (json is Map<dynamic, dynamic>) {
if (ensureUniqueKey) {
final Map<String, dynamic> result = <String, dynamic>{};
json.forEach((dynamic key, dynamic value) {
// ignore: require_future_error_handling
result.putIfAbsent(key.toString(), () => value);
});
return result;
}
return json.map(
(dynamic key, dynamic value) => MapEntry<String, dynamic>(key.toString(), value),
);
}
return null;
}