I'm constructing an object using the following constructor:
class A {
int col;
int row;
A.fromMap(Map<dynamic, dynamic> data)
: col = data['col'],
row = data['row'];
}
class B {
A aObj;
int objType;
int count;
B.fromMap(Map<dynamic, dynamic> data)
: objType = data['objType'],
count = data['count'],
aObj = A.fromMap(data['A']);
}
The problem is that if the map I'm passing in doesn't have a mapping for aObj, it crashes. I have tried moving the assignment into the curly brackets and testing for null:
if(data['A'] != null) {
aObj = A.fromMap(data['A']);
}
This works. But I'd like to test as part of the short cut constructor like in the other data members.
Is that possible?
I think how you can prevent crashes in a neat way is this way:
aObj = A.fromMap(data['A'] ?? Map())
This will return an empty Map
to your custom A.fromMap
constructor when data['A']
is null
, which will result in col
and row
being null
afterwards (if data['A']
is null
) because the fields do not exist in the Map
.
what about a ternary operator?
aObj = data['A'] ? A.fromMap(data['A']) : null;
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