Search code examples
flutterflutter-providerriverpodflutter-riverpod

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


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


Solution

  • 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 show 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: ...,
    )