Null Operators — ??, ??=, ?., !
Null Operators: ??, ??=, ?., and !
With the introduction of Sound Null Safety in Dart, the compiler prevents errors caused by accessing variables that contain null. To make working with nullable values clean and efficient, Dart provides several specialized null-aware operators.
These operators are heavily used in Flutter UI layout development and API response handling.
1. Null Coalescing Operator (??)
The ?? operator evaluates its left-side expression. If the value is not null, it returns it. If the value is null, it evaluates and returns the right-side expression.
dartvoid main() { String? serverName = null; String activeServer = serverName ?? "localhost"; print(activeServer); // localhost }
2. Null-Aware Assignment Operator (??=)
The ??= operator assigns a value to a variable only if that variable evaluates to null. If the variable already holds a non-null value, the assignment is skipped.
dartvoid main() { int? maxUsers; maxUsers ??= 100; // Assigned since maxUsers was null print(maxUsers); // 100 maxUsers ??= 200; // Skipped print(maxUsers); // 100 }
3. Null-Aware Access Operator (?.)
The ?. operator allows you to call a method or access a property on an object that might be null. If the object is null, the entire statement evaluates to null instead of throwing a runtime error.
dartclass User { final String? bio; User(this.bio); } void main() { User? user1 = null; print(user1?.bio); // prints null (no crash!) User user2 = User("Developer"); print(user2.bio?.toUpperCase()); // prints DEVELOPER }
4. Null Assertion Operator (!)
The ! operator forces the compiler to treat a nullable expression as non-nullable. You are asserting: "I guarantee this is not null at this line of execution."
[!CAUTION]
If the value is actually null when this line executes, Dart will throw a TypeError at runtime. Use this operator sparingly.
dartvoid main() { int? age = 21; int parsedAge = age!; // OK - age is not null print(parsedAge); // 21 int? score = null; // int parsedScore = score!; // Throws runtime exception! }
Chaining Null Operators
You can chain null-aware operators together to handle deeply nested JSON or object trees safely.
dartclass Profile { final String? avatarUrl; Profile(this.avatarUrl); } class Account { final Profile? profile; Account(this.profile); } void main() { Account? userAccount = Account(null); // Safely drill down to avatarUrl, fallback to placeholder String avatar = userAccount?.profile?.avatarUrl ?? "placeholder.png"; print(avatar); // placeholder.png }
Summary
- Use
??to provide a fallback value when an expression evaluates tonull. - Use
??=to set a default value on a nullable variable if it hasn't been set yet. - Use
?.to invoke members on objects that might benullto avoid crashing your application. - Use
!only when you are absolutely certain a value is notnulland you want to bypass compile-time checks.