It depends on your context there, but in a nutshell: you've got to choose what to do when even.netPhone
is null
.
Dart is able, in some contexts, to do the type promotion by itself: here's a quick dartpad example (as you can see, no compile-time errors happen):
void main() {
int? a;
a = doSomeWork();
if (a == null) {
print("do something when a is null");
return;
}
if (a.isEven) {
print("do something even");
} else if (a.isOdd) {
print("do something odd");
}
}
int? doSomeWork() {
return 5; // You can change this to any int? value
}
Therefore, in your code you could do something like this:
var myPhone = event.newPhone;
if (myPhone == null) {
print("Do something when there's no phone");
return;
}
if (myPhone.length > 7) { // No null-aware operators needed
print("Actions when the phone is not null");
}
As you can see, the return
statement lets Dart infer the type promotion. If you can't return (again, depends on your logic), use the !
operator to help it do so.
IMPORTANT NOTE / EDIT. As suggested by @jamesdlin, This only works with a local variable. At the moment I'm writing this, there are several Dart open issues on github to let Dart infer more about non-nullability promotion.