4

I was wondering what use case exists for the FutureProvider class?

I am particularly interested how to load an asynchronous function like Future<Contact> getAllContacts() async { ... } when the ui is built with a FutureProvider, ChangeNotifierProvider or anything similar.

Moreover, each time when notifyListeners() is called, I would like to have that provider to rebuild the ui with asynchronous call. Is that any way possible with provider or am I missing something?

thehayro
  • 1,516
  • 2
  • 16
  • 28

1 Answers1

9

FutureProvider doesn't come with a built-in update mechanism – but can be combined with Consumer and a mutable object (ChangeNotifer or State) to handle updates.

It has two main usages:

  • Exposing an "immutable value" that needs to be asynchronously loaded (a config file for example):
FutureProvider<MyConfig>(
  builder: (_) async {
    final json = await // TODO load json from something;
    return MyConfig.fromJson(json); 
  }
)
  • Alternatively, it can be combined with something that can mutate (like ChangeNotifier) to convert a Future into something easier to manipulate:
ChangeNotifierProvider(
  builder: (_) => Foo(),
  child: Consumer<Foo>(
    builder: (_, foo, __) {
      return FutureProvider.value(
        value: foo.someFuture,
        child: ...,
      );
    },
  ),
);
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • Thank you. I was able to create a [gist](https://gist.github.com/hayribakici/b7aa6486aec9aa947ce9432c3de13c13) based on your answer that allows to display a child while the future operation is in progress. – thehayro Aug 17 '19 at 12:24
  • Is there a way to set the provider when the Future returns? – Jessica Sep 20 '19 at 01:25
  • 2
    Is there a clean way of using this pattern within `MultiProvider` ? – Matt Jan 23 '20 at 00:05
  • 5
    I appreciate your development of the Provider package but the sound logic eludes me for why there is a FutureProvider but not the likes of a "FutureChangeNotifierProvider". The latter seems like it would be the more common use case for state management, albeit harder to implement than the former. – Brian Ogden Apr 06 '20 at 04:09
  • @brianodgen because as soon as non nullable types are released, this would stop working – Rémi Rousselet Apr 06 '20 at 06:03
  • @RémiRousselet Would you provide us with a way to register change notifier proxy providers that depend on asynchronous work? I sent you an email and posted a question on this topic but haven't heard back. – Barry Dec 10 '21 at 19:13