I am decoding a JSON string using Dart/Flutter, and I want to make sure that the resulting Map
has all the keys I expect.
return MyRecord(
id: jsonObj['id'],
name: jsonObj['name'],
description: jsonObj['description']
);
I thought I would get an exception if I tried to access a key that doesn't exist in the map, but Dart silently returns null
instead. I guess I could simply use something like
if( !(jsonObj.containsKey('id')
&& jsonObj.containsKey('name')
&& jsonObj.containsKey('description')) )
throw new ArgumentError('Invalid JSON for converting to MyRecord: $jsonObj');
But I'm hoping there's a more convenient way to achieve what I want?
Map[key] returns null if key is not in the map. It could instead throw an exception, consistent with collections such as List and Queue. The upside would be possibly more robust code (assuming that not all map[key] call-sites check for null), the downside..
containsKey() function in Dart is used to check if a map contains the specific key sent as a parameter. map. containsKey() returns true if the map contains that key, otherwise it returns false .
A Dart Map allows you to get value by key. What about getting key by value? Using the keys property and the firstWhere() method of the List class, we can get key by specifying value . The Dart method firstWhere() iterates over the entries and returns the first one that satisfies the criteria or condition.
remove() function in Dart removes a specific element (key-value pair) from the map. If the key is found in the map, the key-value pair is removed and the key is returned.
Still not super convenient, but a possibility:
MyRecord(
id: jsonObj['id'] ?? (throw ArgumentError("id is required")),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With