Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 551
iDecode Avatar asked Oct 16 '25 22:10

iDecode


1 Answers

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.

like image 124
jamesdlin Avatar answered Oct 20 '25 00:10

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!