简体   繁体   中英

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

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?

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:-)

Wouldn't this example help to solve it? The problem of navigation is there reduced to manipulating an immutable collection.

Strictly typed navigation is used. You can use navigate([Home(), Books(), Book(id: bookId)]); instead of navigate('home/books/$bookId'); in your code.

See riverpod_navigator_example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM