Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case for FutureProvider

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?

like image 602
thehayro Avatar asked Jan 27 '23 00:01

thehayro


1 Answers

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: ...,
      );
    },
  ),
);
like image 168
Rémi Rousselet Avatar answered Feb 03 '23 15:02

Rémi Rousselet