2

I've been reviewing the RiverPod 2 tutorial at https://codewithandrea.com/articles/flutter-state-management-riverpod/

In the section dealing with Future providers there is a code snippet as shown below...

final weatherFutureProvider = FutureProvider.autoDispose<Weather>((ref) {
  // get repository from the provider below
  final weatherRepository = ref.watch(weatherRepositoryProvider);
  // call method that returns a Future<Weather>
  return weatherRepository.getWeather(city: 'London');
});

I can't understand why this code snippet is missing the 'async' and 'await' syntax as shown below...

final weatherFutureProvider = FutureProvider.autoDispose<Weather>((ref) async {
  // get repository from the provider below
  final weatherRepository = ref.watch(weatherRepositoryProvider);
  // call method that returns a Future<Weather>
  return await weatherRepository.getWeather(city: 'London');
});

Is my version correct or what?

user2868835
  • 1,250
  • 3
  • 19
  • 33

1 Answers1

4

Think of it as doing:

Future<int> example() {
  return Future.value(42);
}

instead of:

Future<int> example() async {
  return await Future.value(42);
}

Sure, you can use async/await. But it is technically optional here.

Doing return future vs return await future doesn't change anything. In fact, there's a lint for removing the unnecessary await: unnecessary_await_in_return

The async keyword is generally helpful. It catches exceptions in the function and converts them into a Future.error.
But FutureProvider already takes care of that. So async could also be omitted

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • Oh interesting, so this is a dart feature that it awaits futures instead of returning them? – jaaq Nov 11 '22 at 09:23