In flutter with riverpod, how to update state on a page already in the navigation stack

Issue

I have some flutter/riverpod/navigator 2.0 pages that follow this flow.

list of items page -> navigate to -> edit item page -> back button -> list of items page.

the issue is when one hits the back button, the list of items is not updated with the new content, since that page is cached in the navigation stack of pages.

Are there any suggestions on how to handle this case?

Solution

Ok I just got it working! The very short version is use a Consumer nested inside a ProviderListener on your 1st form. For me the 1st form shows a list of retrieved models. On that list page I have…

  Widget build(BuildContext context) {
    return ProviderListener(
      onChange: (context, state) {
      // Below Model.save in provider sets state to
      // "Success(model)". This triggers here and we
      // List.update in provider to update fields in
      // the Model in the List. Then the Consumer
      // below triggers on "Data(model)" state and the
      // List refreshes and shows updated Model
      if (state is Success) {
          context.read(regionListNotifierProvider.notifier).update(state.model);
        }
      },
      provider: regionNotifierProvider,
      child: Consumer(builder: (context, watch, child) {
        final state = watch(regionListNotifierProvider);

On the List page, each Tile is clickable. When you click it uses the Model provider to set state to the Model you just clicked. Then it Naviatates to the form. The form reads state and see the info for the Model you clicked in the List.

In my ModelForm (where you edit the Model fields), when you save that fires the save method in it’s provider. In there, it fire the .update above then the ModelForm Navigator.pops back to the List page, then above Listener and Consumer trigger in sequence and the List shows the updated data.

NOTE: The ProviderListener is listening to the ModelForm provider, then the Consumer is listening to the List provider. Follow? This is THE trick that finally worked!

NOTE2: These are all Stateless widgets. Only need the states in the Riverpod providers. They do everything.

NOTE3: These 2 providers talk back-n-forth. List gives the clicked model to form, when form saves, the List page hears that and updates it list of Models

I’m happy to add more details if you need them 🙂

Answered By – Locohost

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.