Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of void async function in Dart

Tags:

dart

In Dart, if you have an async function that doesn't return anything, should it return Future<void> or simply void? Both seem to work, but why?

void foo() async {
  print('foo');
}

Future<void> bar() async {
  print('bar');
}

void main() async {
  await foo();
  await bar();
  print('baz');
}

Compiles with no errors or warnings and prints

foo
bar
baz
like image 819
Timmmm Avatar asked Nov 19 '19 17:11

Timmmm


People also ask

Can async method have void return type?

Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods return void if they run synchronously.

Can async return void?

Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.

What is the return type of async await?

The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

How do you return a void in darts?

In a large variety of languages void as return type is used to indicate that a function doesn't return anything. Dart allows returning null in functions with void return type but it also allow using return; without specifying any value. To have a consistent way you should not return null and only use an empty return.


1 Answers

In your code, both functions foo() and bar() are not returning anything so any function return type is valid for both functions eg:

void/T/Future<T>... foo() async {
  print('foo');
}

Future<void>/T/Future<T>... bar() async {
  print('bar');
}

and here,

await foo();
await bar();

await just waits till the execution of these async functions is complete. As there is no return type, await has no purpose here(redundant) so this is and should not be a compilation error.


The difference is that Future<void> gives you information of the execution of the function like when the execution is complete and it also allows you to specify what to do when the function is executed by using bar().then(...) and bar().whenComplete(...).

While foo() function return void and void does not hold as such any info like Future<void>. If you try to await bar() it will convert that Future object from Future<void> to void.


Future is just a container, with await returns the values once the async "tasks" are completed. Without await, Future objects give you information about the execution of the function from which they are returning.

like image 161
FutureJJ Avatar answered Oct 20 '22 02:10

FutureJJ