Dart 2: Difference between Future<void> and Future<Null>
Asked Answered
C

1

16

Having an asynchronous function that doesn't return a value, what's the ideal return type Future<Null> or Future<void>?, or more specifically, what's the difference in using either? Both are legal, and in both cases the return value of the function is a Future that resolves to null. The following code prints null two times:

import 'dart:async';

Future<void> someAsync() async {}
Future<Null> otherAsync() async {}

main() {
    someAsync().then((v) => print(v));
    otherAsync().then((v) => print(v));
}
Calliecalligraphy answered 21/3, 2018 at 15:17 Comment(0)
M
21

The type Null only allows the value null

The type void allows values of any type, but communicates that the value shouldn't be used.

It's not yet clear to me how tools support will treat void. There will probably linter rules that hint or warn at using void values.

Null was used instead of void previously because void was only supported as return type of methods/functions.

Miramirabeau answered 21/3, 2018 at 15:24 Comment(2)
Using void to accept any return value goes against the dart 2 policy of strong typing, so I guess that in the future returning a value with Future<void> won't be allowed, also Null doesn't make sense as a type so my guess is that it will disappear in the future. Nice answer, thanks.Calliecalligraphy
No void will become much more common. void allows any return value, but callers will get a warning if they use the return value. Dart tries to get out of your way and if void would not allow any value, () => foo() would cause an error because of the implicit return. See also this comment from eernstgEntrust

© 2022 - 2024 — McMap. All rights reserved.