skip to Main Content

I have a very weird scenario with my Riverpod Providers.

I have two providers, which are a list of a custom object, SiblingModel.

Here are the providers defined:

final siblingsListProviderSD = StateProvider<List<SiblingModel>>(
      (ref) => [],
);
final deleteListSiblingsProviderSD = StateProvider<List<SiblingModel>>(
      (ref) => [],
);

At certain point in the app, I am editing the data of one of the providers. Like this:

ref.read(siblingsListProviderSD.notifier).state[index].fields?.name = 'DUMMY NAME';

Now, something very strange is happening, that this value is changing in the list of both of these providers

So for example, after changing it like above, if I Print the result of both providers like this:

 print('Upload Item 1 name: ${siblingsListToUpload.first.fields?.name}');
 print('Delete Item 1 name: ${siblingsListToDelete.first.fields?.name}');

The output that I get for both is ‘DUMMY NAME’, even though I only changed the value ot eh sublingsListToUpload provider, not the other one.

Why are the values in both providers changing?

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    I don't know why, but the issue was that I wasn't using copyWith.

    When I did it like this, it worked:

      ref.read(siblingsListProviderSD.notifier).state[index] =
                        ref.read(siblingsListProviderSD.notifier).state[index]
                            .copyWith(fields: ref.read(siblingsListProviderSD.notifier).state[index].fields?.copyWith(name: text));
    

  2. If I understand correctly, then you can try to track the problem like this:

    import "package:riverpod/riverpod.dart";
    
    final list1 = StateProvider<List<int>>((ref) => []);
    final list2 = StateProvider<List<int>>((ref) => []);
    
    void main() {
      final container = ProviderContainer();
    
      container.read(list1).add(5);
    
      final item1 = container.read(list1);
      final item2 = container.read(list2);
    
      print(item1);
      print(item2);
    }
    

    Only in this case everything works as expected. Do you have a minimal example to reproduce?

    It seems to me that your SiblingModel object is not so simple. And the problem lies precisely in it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search