Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger an exception when accessing an invalid key from a map in Dart

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?

like image 874
Magnus Avatar asked Feb 06 '19 12:02

Magnus


People also ask

Does map throw exception if key not found?

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..

How do you check if a key exists in a map Dart?

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 .

How do you value a key from a Dart map?

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.

How do you remove a key-value pair from a Dart map?

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.


1 Answers

Still not super convenient, but a possibility:

MyRecord(
  id: jsonObj['id'] ?? (throw ArgumentError("id is required")),
like image 190
Ski Avatar answered Oct 08 '22 00:10

Ski