7

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'); 
}
ln 1214
  • 123
  • 1
  • 4

2 Answers2

8

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>.

hola
  • 3,150
  • 13
  • 21
-1
Future<void> myMethod() async{ } 

is a asynchronous function which means it let the app to work while waiting for some operation to finish(ex:Network Request).The Future fun(); is used while we need to perform operation that gives result in future such as network call.

void fun(){};

is function that doesnot return anything.

Khadga shrestha
  • 1,120
  • 6
  • 11