Paul Cbt
Paul Cbt

Reputation: 143

Dart null safety !. vs ?-

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?

Upvotes: 0

Views: 1406

Answers (4)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63594

?. 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.

Upvotes: 6

Poran
Poran

Reputation: 602

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.

Upvotes: 0

Stefan Galler
Stefan Galler

Reputation: 831

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

Upvotes: 0

Diwyansh
Diwyansh

Reputation: 3514

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.

Upvotes: 3

Related Questions