Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Future<void> vs void [duplicate]

Tags:

flutter

dart

Say I want to create an asynchronous method. I can make its return type either Future void or simply "void" (as in examples below). Both ways seem to do the trick. So what's the difference between the two? When should I use Future void instead of void? Thanks!

Future<void> myMethod() async{ 
  await myOtherMethod(); //myOtherMethod() has return type of Future<void>
  print('something'); 
}

vs

void myMethod() async{ 
  await myOtherMethod(); //myOtherMethod() has return type of Future<void>
  print('something'); 
}
like image 225
ln 1214 Avatar asked Apr 26 '26 05:04

ln 1214


1 Answers

Use Future<void> where you want to

Call future functions:

myMethod().then((_) => ...).catchError((err) => ...);

Use await for more readable async code.

await myMethod();
await anotherMethod();

Use void where you want to fire and forget.

myMethod();
... do other stuff

The Future<void> is a lot more common. If you're not sure which one to use, use Future<void>.

like image 71
hola Avatar answered Apr 29 '26 20:04

hola