Home > Net >  Flutter - Riverpod Future Provider: How to keep old data when error occurs
Flutter - Riverpod Future Provider: How to keep old data when error occurs

Time:12-28

This is my usecase:

  1. data is downloaded

    final dataProvider = FutureProvider<MyModel>((ref) async { 
        return fetchData(); 
    });
    

and it's used like this within widget's build method:

  ref.watch(dataProvider).when(
    data: DataWidget(data), 
    error: ErrorWidget(), 
    loading: LoadingWidget())
  1. user has option to refresh the data:

    ref.refresh(dataProvider.future);
    

But when there is an error (for example phone is in airplane mode) error is provided so DataWidget is lost and replaced with ErrorWidget... Is there a way using Riverpod to provide/keep existing data instead of error ? I believe it's common scenario, but I didn't find any elegant solution for this problem. I've also read documentation too, but didn't find anything helpful related to this. Am I missing something ? (I'm new to Riverpod) Thank you

CodePudding user response:

Preserving the previous data on refresh is behavior as part of 2.0.0.
Although there were some bugs that you may have encountered. Make sure youre using 2.1.3 or above, which should fix all the issues related to this.

As for using when to how the previous data/error, you can use various flags:

asyncValue.when(
  // show previous data/error on loading
  skipLoadingOnReload: true,
  // show previous data if there's an error
  skipError: true,
  loading:...,
  data:...,
  error: ...,
)

CodePudding user response:

In the new version of Riverpod (as of v.2.1.0), you can do this:

asyncValue.when(
  optimistic: !asyncValue.hasError,
  data: DataWidget(data), 
  error: ErrorWidget(), 
  loading: LoadingWidget(),
)

You can see more details here.

  • Related