Home > other >  Flutter Riverpod Future provider - requires async and await?
Flutter Riverpod Future provider - requires async and await?

Time:11-11

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?

CodePudding user response:

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

CodePudding user response:

That's because futures are values that will be available sometime in the future. The idea is that you can use an asynchronous function to call e.g. a web API and then await the result only at the moment you need it. This way you can do other stuff while the Future is mostly waiting. Check the docs for more on the topic.

  • Related