Shorthand of checking the nullability of a bool variable used in an if condition

Issue

Future<bool?> f() async => true;

void main() async {
  final proceed = await f();
  if (proceed) {...} // Error
  if (proceed != null && proceed) {...} // Works but too verbose
}

Is there any shorthand or a better way of proceeding instead of writing a long proceed != null && proceed check? I know I might be missing something so trivial.

Note: I know a default value can be provided to proceed but that’s just not my use case. Bang operator can do the trick iff bool is actually not null.

Solution

Sounds like a case where you can use the ?? operator which are documented here in the language tour:
https://dart.dev/guides/language/language-tour#conditional-expressions

It will allow you to rewrite your long if-statement into:

if (proceed ?? false) {...}

?? means here that we want to use the value of proceed as long as it is not null. In case of null we want to use false as the value.

One drawback of this is that it does not seem like Dart makes any type promotion of proceed compared to the following where proceed afterwards is promoted to a non-nullable type:

if (proceed != null && proceed) {...}

Not sure if there are a Dart issue on that.

Answered By – julemand101

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *