Dart中?.操作符具体检查什么?相关使用疑问咨询
?. Operator (Optional Chaining) Hey there! Let's break down all your questions about Dart's ?. operator clearly—this is such a handy tool once you wrap your head around it, so awesome that you're digging into the details as a new Dart developer.
What does the ?. operator actually check?
The ?. is Dart's optional chaining operator. Here's what it does step by step:
- It first checks if the object before the
?.(in your example,subscription) isnull. - If the object is not null, it proceeds to execute the method or access the property that comes after the
?.(so it callscancel()in your code). - If the object is null, it stops right there—no method is called, no property is accessed, and the entire expression just returns
null.
Think of it as a shorthand for writing:
if (subscription != null) { subscription.cancel(); }
But in a single, cleaner line of code.
Is it a non-null check?
Absolutely! This operator is designed specifically for safe non-null checks when accessing members (methods or properties) of an object. It's a defensive way to avoid the dreaded NullPointerException that happens when you try to call a method on a null object.
Just to clarify: it's different from the ! (null assertion operator), which forces Dart to treat a nullable object as non-null (and will throw an error if it actually is null). The ?. operator is safe—it never throws an error if the object is null.
Can it be used with Widgets?
Yes, absolutely! You'll use this all the time in Flutter when working with nullable Widgets or nullable properties of Widgets.
For example:
- Suppose you have a nullable Widget variable like
final Widget? customAppBar; - You can safely access its properties with
customAppBar?.key—ifcustomAppBaris null, this just returns null instead of crashing. - Or if you have a nullable state object that builds a Widget:
myNullableState?.build(context)will only runbuild()ifmyNullableStateexists.
It's super useful in build methods where certain Widgets might be conditionally null (like optional headers, footers, or dynamic content).
What happens if the object is null?
If the object before ?. is null, two key things happen:
- The method/property access after
?.is not executed at all—so in your example,cancel()won't be called ifsubscriptionis null. - The entire expression evaluates to
null.
This means you don't have to worry about runtime errors from trying to interact with a null object. If you chain multiple optional calls (like subscription?.cancel().then((_) => print('Done'))), the chain stops at the first null—so then() won't run either, and the whole thing returns null.
内容的提问来源于stack exchange,提问作者Keerti Purswani

