Reputation: 2287
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?
Upvotes: 4
Views: 7626
Reputation: 267434
With NNBD introduced in Dart 2.8, you can use:
class Foo {
final int value;
// 0 is the default value in case the expression data['key'] returns null
Foo.fromNonNullable(Map data) : value = data['key'] ?? 0;
// 0 is the default value in case `data` is `null`
Foo.fromNullable(Map? data) : value = data?['key'] ?? 0;
}
Upvotes: 0
Reputation: 126634
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
.
Upvotes: 5
Reputation: 2662
what about a ternary operator?
aObj = data['A'] ? A.fromMap(data['A']) : null;
Upvotes: 4