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
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?
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.
Double dots(..) It allows you to not repeat the same target if you want to call several methods on the same object.
double question mark operator means "if null".
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With