Liu Silong
Liu Silong

Reputation: 5532

How to reset the state of FutureProvider in Riverpod

Problem description:

  1. When the user enters the page, loading is displayed, and then the network request is automatically executed.
  2. If the request is successful, the relevant data is displayed.
  3. If the request fails, a custom error page is displayed, which has a Reload button
  4. Ideally, if the user clicks the Reload button, the network request will be re-executed, and the page should re-enter the loading state and display the loading page
  5. The problem is that after the first loading fails, the user manually triggers the network request by clicking the Reload button, and the page does not re-enter the loading state, but waits until the data request is successful and then displays the data directly, and does not enter the loading state before the request comes back.

The code is as follows

@riverpod
Future<String> getUserInfo(GetUserInfoRef ref) async {
  ResponseModel res = await TestApi.getUserInfo();
  return res.data['name'];
}

// UI Page
Widget build(BuildContext context) {
    final request = ref.watch(getUserInfoProvider);
    return Scaffold(
      appBar: AppBar(title: const Text("MyPage2")),
      body: switch (request) {
        AsyncData(:final value) => Text(value),
        AsyncError(:final error) => MyErrorWidget(
            onReload: () {
              // Reload button click callback
              ref.refresh(getUserInfoProvider);
            },
          ),
        _ => const CircularProgressIndicator(color: Colors.red),
      },
    );
  }

I tried refreshing the provider, but it didn't work. I hope there is a way to make the provider state start from loading when refreshing the provider. Otherwise, I can only add a loading widget in MyErrorWidget to handle it.

Upvotes: 0

Views: 132

Answers (1)

Dan R
Dan R

Reputation: 1326

I would recommend having a look at the riverpod documentation showing how to implement pull to refresh.

In the example mentioned above, to refresh a FutureProvider:

onRefresh: () => ref.refresh(getUserInfoProvider.future),

is used.

Upvotes: 1

Related Questions