DART / CHAPTER 01
Types, bindings, and null safety
BeginnerRepresent values and absence explicitly in Dart.
By the end of this chapter
- Distinguish final from const
- Use nullable types deliberately
- Predict division and fallback results
The idea
Dart variables have types even when var lets the compiler infer them. final permits a binding to be assigned once, while const creates a compile-time constant value where a constant expression is available. Neither keyword is a substitute for understanding the object being referenced: a final list can still be mutable. Nonnullable types exclude null unless a question mark marks the type as nullable.
The operator ?? supplies a fallback only for null, not for zero or an empty string. Use ?. when accessing a member through a possibly absent receiver. For arithmetic, / produces division with a fractional result, while ~/ truncates the quotient toward zero. Select the operation from the requirement instead of relying on the destination variable to fix it.
void main() {
int? stored;
final count = stored ?? 7;
print(count ~/ 2);
print(count / 2);
}3 3.5
The uninitialized nullable local starts as null, so count becomes seven. The two division operators deliberately request different results.
Try it yourself
Return an optional label’s length, using zero only when the label is absent.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING