Dart guide
tip
=> Arrow Syntax for function { return ...; }
This arrow syntax is a way to define a function that executes the expression to its right and returns its value.
bool hasEmpty = aListOfStrings.any((s) {
return s.isEmpty;
});
is same as
bool hasEmpty = aListOfStrings.any((s) => s.isEmpty);
Null safety
declaring variables supporting null
int? x = null;
int? a; /// it ahs null as default value
null aware operators ??= & ??
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? a; // = null
a ??= 3;
print(a); // <-- Prints 3.
a ??= 5;
print(a); // <-- Still prints 3.
Another null-aware operator is `??`, which returns the expression on its left unless that expression’s value is null, in which case it evaluates and returns the expression on its right:
print(1 ?? 3); // <-- Prints 1.
print(null ?? 12); // <-- Prints 12.
Conditional property access
conditional member access operator
?.
myObject?.someProperty ⏩ means (myObject != null) ? myObject.someProperty : null
// Example::
// This method should return the uppercase version of `str`
// or "null" if `str` is null.
String? upperCaseIt(String? str) {
return str?.toUpperCase();
}
tip
myObject?.someProperty
same as
(myObject != null) ? myObject.someProperty : null
Cascade ..
class User {
String name, email;
Address address;
void sayHi() => print('hi, $name');
}
class Address {
String street, suburb, zipCode;
void log() => print('Address: $street');
}
void main() {
User()
..name = 'Alex'
..email = 'alex@example.org'
..address = (Address()
..street = 'my street'
..suburb = 'my suburb'
..zipCode = '1000'
..log())
..sayHi();
}
myList..add("item1")..add("item2")…..add("itemN");
⏬ ⏬ ⏬ /// can be easily written as
myList.add("item1").add("item2")….add("itemN");
//cascading operator discards the result, and returns the original receiver 'myList'
Another Example of Cascade
class Node {
String key;
Node(this.key);
Node left;
Node right;
}
void main() {
Node right = new Node('e');
Node root = new Node('root')
..left = (new Node('a')
..left = (new Node('b')
..left = new Node('c')
)
..right = Node('d')
)
..right = right;
print(root);
}