rrousselGit / provider

InheritedWidgets, but simple
https://pub.dev/packages/provider
MIT License
5.1k stars 509 forks source link

The shouldUpdate Selector method returns the same previous and next values #853

Closed PLynx01 closed 8 months ago

PLynx01 commented 8 months ago

Describe the bug When using the Selector of the List, the shouldUpdate Selector method returns the same previous and next values, even though the List was overwrittten by the modified version.

Expected behavior The changes in List should return the different previous and next values, whith the changes in list

This works when adding entries to the list (the previous and next values are different):


void addOption(OptionModel optionModel) {
    optionModel.index = options.length;
    options = [...options, optionModel];
    notifyListeners();
  }

But this doesn't work when modyfying the list (previous and next are the same)

void setFrequencyPreset(int optionIndex, FrequencyPresetModel? preset) {
    options[optionIndex].frequencyPreset = preset;

    options = [...options];

    notifyListeners();
 }

And doing this when removing the entries, also doesn't work (previous and next are the same)

 void removeOption(int index) {
    options = options..removeAt(index);

    for (int i = 0; i < options.length; i++) {
      options[i].index = i;
    }

    notifyListeners();
  }

Here is the Selector class from my project:


Selector<OptionsProvider, List<OptionModel>>(
              selector: (context, provider) => provider.options,
              builder: (context, value, child) {

                return Column(
                    children:
                        value.map((model) => OptionTemplate(model)).toList());
              },
              shouldRebuild: (previous, next) {

                log(previous[0].frequency.toString());
                log(next[0].frequency.toString());

                log(previous.length.toString());
                log(next.length.toString());

                return true;
              },
            )

Could someone help me out?

rrousselGit commented 8 months ago

You're modifying the previous list before submitting a new one.

Rather than:

void setFrequencyPreset(int optionIndex, FrequencyPresetModel? preset) {
    options[optionIndex].frequencyPreset = preset;

    options = [...options];

    notifyListeners();
 }

You may want:

void setFrequencyPreset(int optionIndex, FrequencyPresetModel? preset) {    
    options = [...options];
    options[optionIndex].frequencyPreset = preset;

    notifyListeners();
 }

The order matters.