Home > front end >  Provider - Does the declaration for a method have to be in the extended ChangeNotifier for it to upd
Provider - Does the declaration for a method have to be in the extended ChangeNotifier for it to upd

Time:09-23

Context

I have a bottomsheet with a bunch of checkboxes that toggle different options in a filter that returns a list. I have declared a function applyFilters() in its own file which

  1. Empties the old list.
  2. Applies all the new values from the check-boxes into the filtering function.
  3. Adds a card in the the list for each of the items in the new list to the displayed list.

I used to call this function in a setstate in the build method. But i am introducing Provider so i can get rid of all the prop drilling.

Everything works. Except provider doesn't see that it needs to rebuild the ListView that displays all the items.

To summarize

  • Checkboxes are working and updating with provider.
  • Applying the filters work correctly.
  • ChangeNotifierProvider placed at root of app.
  • Even though applyFilters()changes the contents of the displayed list used by the Listview Provider does not rebuild that part of the UI.

Question

Could it be because the applyfilters() method is only called inside the extende ChangeNotifier and provider can only see the effects it has on the UI if its declared inside it?

Image of app-screen and code.

Here is a picture of the bottom-sheet and the list on the main page that i wish to rebuild. enter image description here


And here is a simplified view of my extended ChangeNotifier:

class PreferenceCheckboxDataHandler extends ChangeNotifier {

void updateOption1ValueAndState () {

    applyFilters();
    notifyListener
  }
}

And here is the relevant parts of code in the main.dart enter image description here

enter image description here

Intention

As i have watched too many hours of tutorials on Provider without increasing my understanding. (decided to stick with Provider) I hope to gain insight if this may be the simple reason for my problem or i need to completely change my approach.e.g Another package.

CodePudding user response:

If your displayedCards does not contain the Provider instance in the UI then it will not update, when you notifyListeners(); but you can make use of Consumer to update the UI.

body: Consumer<PreferenceCheckboxDataHandler>(
  builder: (context, value, _) {
    return ListView(children: displayedCards);
  },
);
  • Related