Kagawa
Kagawa

Reputation: 1359

FutureProvider using .whenData() shorthand

Riverpod provides a shorthand using .whenData() where you do not need to supply loading and error parameters. But I can't find example of how this code can be used to return widget in build() function.

     Widget build(BuildContext context, ScopedReader watch) {
          final cityListFuture = watch(cityListFutureProvider);
          // This one is working fine
          return cityListFuture.when(
              data: (value) {
                return Text("Data goes here");
              },
              loading: () => CircularProgressIndicator(),
              error: (error, stack) {
                return Container();
              });
     
          // This is shorthand for .when() without the need of loading and error
          // ERROR: The return type 'AsyncValue<Text>' isn't a 'Widget', as required by the closure's context.
          return cityListFuture.whenData((value) => Text("Data goes here"));
     }

Anyone knows how can we use .whenData() to return a widget?

Upvotes: 3

Views: 3706

Answers (2)

Trung B&#249;i
Trung B&#249;i

Reputation: 1

Now it is return cityListFuture.whenData((val) => Text(val)).asData!.value;

Upvotes: 0

Nisanth Reddy
Nisanth Reddy

Reputation: 6430

Quite an interesting documentation I had to go through for this.

It seems like the whenData is probably not exactly what is sounds like it should do.

Because all it does is that it return an AsyncValue<Widget> instead of directly returning Widget like the when function does.

So one way to use it would be,

return cityListFuture.whenData((val) => Text(val)).data!.value;

Here, the value would be your Text(value) itself.

One thing to be careful of here is the ! symbol since the data can be null. So you would have to manually have if checks.

Other thing to note here is that, you might as well achieve the same thing with something like this,

return Text(watch(cityListFutureProvider).data?.value);

Assumptions have been made that your value is a String.

Upvotes: 2

Related Questions