Home > other >  Dart null safety !. vs ?-
Dart null safety !. vs ?-

Time:12-28

what is the difference exactly between

String id = folderInfo!.first.id;   //this works

and

String id = folderInfo?.first.id; //this is an error

I know ?. returns null when the value object is null but what does the !. return?

CodePudding user response:

The Assertion Operator (!)

Use the null assertion operator ( ! ) to make Dart treat a nullable expression as non-nullable if you’re certain it isn’t null.

In other words !. will throw an error if the value is null and will break your function and as you know ?. will return null with no interruption.

CodePudding user response:

?. is known as Conditional member access

the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)

In your case, String id means id can not have null value. But using ?. can return null that's why it is showing errors.

!. is use If you know that an expression never evaluates to null.

For example, a variable of type int? Might be an integer, or it might be null. If you know that an expression never evaluates to null but Dart disagrees, you can add ! to assert that it isn’t null (and to throw an exception if it is).

More and ref: important-concepts of null-safety and operators.

CodePudding user response:

The ! throws an error if the variable is null. You should try to avoid this if possible.

CodePudding user response:

If you’re sure that an expression with a nullable type isn’t null, you can use a null assertion operator (!) to make Dart treat it as non-nullable. By adding ! just after the expression, you tell Dart that the value won’t be null, and that it’s safe to assign it to a non-nullable variable.

In your first case, you define id not nullable but when you set nullable value then throw error.

String id = folderInfo?.first.id; 

In 2nd case, when you use assertion operator (!), it actually tell compiler that it must be non nullable.

  • Related