Use case for FutureProvider

Issue

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?

Solution

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: ...,
      );
    },
  ),
);

Answered By – Rémi Rousselet

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *