- By default, a function likes
function() {}
returns a null
pointer value.
Use this archetype when your function not return anything and it's not marked as async
:
function() { // <- not async
// ... some code
// ... don't use return
}
- Optionally, you can specify not return values using
void function() {}
sintaxis. It's same at the function() {}
but if you try to assign a value after calling you will get an error in compile time:
Error: This expression has type 'void' and can't be used.
Personally, i recommend this approach if you really don't have a return value and the function it's not async.
Note that you can use void
in normal and async functions.
- A function likes
Future<void> function() async {}
is for asynchronous function thats returns a Future<void>
object.
I personally recommend the void function() async {}
only if you don't use await
ot then
on call your function, otherwise, use Future <void> function() async {}
.
An examples:
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 2));
print('Hello');
}
void main() async {
print(myFunction()); // This works and prints
// Instance of '_Future<void>'
// Hello
// Use this approach if you use this:
myFunction().then(() {
print('Then myFunction call ended');
})
// or this
await myFunction();
print('Then myFunction call ended');
}
void myFunction() async {
await Future.delayed(Duration(seconds: 2));
print('Hello');
}
void main() async {
print(myFunction()); // This not works
// The compile fails and show
// Error: This expression has type 'void' and can't be used.
// In this case you only can call myFunction like this
myFunction();
// This doesn't works (Compilation Error)
myFunction().then(() {
print('Then myFunction call ended');
});
// This doesn't works (Compilation Error)
await myFunction();
print('Then myFunction call ended');
}
- A function likes
Future<Null> function() async {}
returns a Future<null>
object. Use it whenever you return null
. It's not recommended to use it because class Null
not extends from Object
and anything you return marks an error (except statements thats returns a null or explicit null value):
Future<Null> myFunction() async {
await Future.delayed(Duration(seconds: 2));
print('Hello');
// Ok
return (() => null)();
// Ok
return null;
}