Search code examples
flutterasynchronousdartfuture

Is there any difference between just returning a value and by using Future.value(); in Dart?


For example, is there any difference between those two code snippets? In dartpad, they return the same thing at the same time.

Does the function itself infer the returning value as bool from the function declaration (Future<bool>) so that using just 'return' is okay or is there any specific situation that make difference?

A:

Future<bool> anyFunction() async {
 print('start');
 var temp = Future.delayed(Duration(seconds: 5));
 bool result = await getSomeResult();
 print('end');

 return result;
}

B:

Future<bool> anyFunction() async {
 print('start');
 var temp = Future.delayed(Duration(seconds: 5));
 bool result = await getSomeResult();
 print('end');

 return Future<bool>.value(result);
}

Solution

  • As it's been years since no answer but only comments, I'll post what I've found here.

    (Thanks to both @pskink and @UTKARSH-Sharma)

    1. They will give the exact same value. You can choose either of them freely.

    2. For The first return result, Dart will infer the type and wrap it in a Future<bool>.

    3. The second Future<bool>.value(result) is just a more explicit expression.

    In conclusion, they both are valid, choose what you simply prefer.