?) is a refutable pattern matching construct in Dart that matches a value if and only if the runtime value is not null, subsequently binding the unwrapped value to a subpattern. It acts as a combined type promotion and destructuring mechanism, extracting non-nullable types from nullable expressions.
Syntax
The null-check pattern is denoted by appending a question mark (?) directly after a subpattern:
Mechanics
When a nullable value of typeT? is evaluated against a null-check pattern:
- Evaluation: Dart checks the runtime value of the expression.
- Rejection: If the value is
null, the pattern match fails. - Extraction & Promotion: If the value is not
null, Dart unwraps the value, promotes its static type fromT?toT, and passes it to the inner<subpattern>for further matching or variable binding.
Refutable Contexts
Because the null-check pattern can fail (when the value isnull), it is strictly a refutable pattern. It is valid only in refutable contexts, such as if-case statements, switch statements, and switch expressions. In these contexts, a null value simply causes the match to fail, allowing execution to fall through to the next case or bypass the conditional block.
Nested Destructuring
The null-check pattern is frequently nested within collection, object, or record patterns to enforce non-nullability on specific elements during destructuring.Irrefutable Contexts (Compile-Time Error)
The null-check pattern cannot be used in irrefutable contexts, such as standard variable declarations or assignments, because irrefutable contexts require patterns that are guaranteed to match. Attempting to use a null-check pattern in an irrefutable context results in a compile-time error.null value should throw a runtime exception, Dart provides the null-assert pattern (!). The null-assert pattern forces the match and throws if the value is null, making it valid for irrefutable declarations:
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More





