Why do I need to return null for functions with nullable return type?

Issue

I get a warning in this code:

Future<int?> foo() async {
  if (someCondition) return 42;
}

This function has a nullable return type of ‘FutureOr<int?>’, but ends without returning a value.

I’m telling Dart that the Future may complete with a nullable type int?, so why is that I’ve to explicitly return null to get away with the warning?

Solution

It’s a warning, not an error. Warnings are for things that are technically legal but very likely are programming mistakes. It’s much more likely that someone writing that code forgot to handle a code path than it is that they intentionally wanted an implicit return null. An explicit return null additionally makes intent clear and thus is more readable.

Answered By – jamesdlin

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.