Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an question (?) mark and dot (.) in dart language?

say I defined ...

final DocumentSnapshot doc;

variable doc might be null so I use a question mark and dot...

print(widget.doc); // null
print(widget.doc == null); // true
print(widget.doc?.data['name']);

why widget.doc?.data['name'] throw error Tried calling: []("name") instead returning null?

for my understanding ?. to check whether null and if it so will return null

like image 705
karina Avatar asked May 20 '19 14:05

karina


People also ask

What does question mark do in Dart?

Dart offers some handy operators for dealing with values that might be null. One is the ??= assignment operator, which assigns a value to a variable only if that variable is currently null: int?

What does question mark do in flutter?

If you want a variable of type String to accept any string or the value null , give the variable a nullable type by adding a question mark ( ? ) after the type name. For example, a variable of type String? can contain a string, or it can be null.

What is dot dot in Dart?

Double dots(..) It allows you to not repeat the same target if you want to call several methods on the same object.

What does two question marks mean in Dart?

double question mark operator means "if null".


1 Answers

To guard access to a property or method of an object that might be null, put a question mark (?) before the dot (.):

myObject?.someProperty

The preceding code is equivalent to the following:

(myObject != null) ? myObject.someProperty : null

You can chain multiple uses of ?. together in a single expression:

myObject?.someProperty?.someMethod()

The preceding code returns null (and never calls someMethod()) if either myObject or myObject.someProperty is null.

Code example Try using conditional property access to finish the code snippet below.

// This method should return the uppercase version of `str`
// or null if `str` is null.
String upperCaseIt(String str) {
  return str?.toUpperCase();
}
like image 91
Paresh Mangukiya Avatar answered Oct 13 '22 00:10

Paresh Mangukiya