Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to test for null in Dart constructor

Tags:

flutter

dart

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?

like image 849
JustLearningAgain Avatar asked Jan 02 '23 06:01

JustLearningAgain


2 Answers

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.

like image 127
creativecreatorormaybenot Avatar answered Jan 10 '23 20:01

creativecreatorormaybenot


what about a ternary operator?

aObj = data['A'] ? A.fromMap(data['A']) : null;
like image 37
vbandrade Avatar answered Jan 10 '23 20:01

vbandrade