A nullable type communicates that a value can be absent. That absence might be an expected state, such as an optional nickname, or a sign that an operation could not find a result.
Check before using
String greeting(String? nickname) {
final clean = nickname?.trim();
if (clean == null || clean.isEmpty) return 'Hello, curious builder';
return 'Hello, $clean';
}
void main() {
print(greeting(null));
print(greeting(' '));
print(greeting(' Noor '));
}Use defaults that preserve meaning
?? supplies a value when the expression on its left is null. It does not handle an empty string, zero or every form of invalid data. Decide what counts as missing for the particular domain.
Avoid guessing with the bang operator
value! tells the runtime you believe the value is not null. If that belief is wrong, the program fails. Prefer a check that makes the proof visible to the reader.
late is useful when initialization follows a known lifecycle, but reading before assignment still fails. It is not a general replacement for a nullable design.
Follow each branch before removing a check
nickname?.trim returns null when nickname is absent; otherwise it trims the string. The next condition handles both absence and an empty result. Only after that proof does the function construct a personalized greeting.
The default is meaningful for this optional nickname. A missing account ID or price may need rejection instead. Null handling should preserve the domain meaning, not universally replace missing data with an empty string or zero.
Use map lookups to practise absence. Avoid replacing checks with ! merely to silence a type error; the assertion moves the failure to runtime rather than resolving the uncertainty.
Try it yourself
Write a function that looks up a duration in a map. Return a useful label when the key is missing, and handle an explicit zero duration differently. Explain why using ! would hide the missing-key case.