Home > Back-end >  Flutter/Dart - Difference between obj!.property and obj?.property
Flutter/Dart - Difference between obj!.property and obj?.property

Time:09-08

In Flutter/Dart their is the null safety feature. In my scenario, I have null safety ON and I am trying to get the property 'myDateTime' of my object MyDateTime . But the compiler produce the error:

The property 'myDateTime' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').

which makes sense because the object can be null.

I tried both solution

MyDateTime!.myDateTime 

and

MyDateTime?.myDateTime 

and the both work fine but I don't understand the difference!! Can anyone elaborate?

CodePudding user response:

MyDateTime!.myDateTime means: i know MyDateTime can never be null and it tries to access property myDateTime even if MyDateTime is null.

MyDateTime?.myDateTime means: i know MyDateTime can be null, so if it is, don't try to access property myDateTime

The first one returns an error if MyDateTime is null, the other one does not.

  • Related