1

I have to state providers. The second one (listWithGlobalIDProvider) depends on the first one (currentListProvider) but the first one is independent. But Adding value to the second provider changes the first provider's value. I am calling the listWithGlobalIDProvider inside a futterProvider.

final currentListProvider =
    StateProvider.autoDispose<BracketList>((ref) {
  final brackets = ref.watch(_currentUserBracketListFutureProvider).value;
  ref.keepAlive();
  return brackets ?? [];
});

final listWithGlobalIDProvider =
    StateProvider.autoDispose<BracketList>((ref) {
  final brackets = ref.watch(currentListProvider);
  final List<String> list = brackets;
  list.add(GlobalBracketID.globalBrackerID);
  ref.keepAlive();
  return list;
});
flutter_riverpod: ^2.2.0

I am expecting that calling the second stateProvider not change the first provider value.

monzim
  • 526
  • 2
  • 4
  • 13

1 Answers1

-1

If I understand your question correctly, you could change the line

final List<String> list = brackets;

to instead be

final List<String> list = List<String>.from(brackets);

This should ensure that modifying the second provider won't change the first provider.

Plonetheus
  • 704
  • 3
  • 11
  • Thanks, it worked. But did not understand what is happing here? Can you explain? – monzim Mar 02 '23 at 16:17
  • In your version of the code, we are not making a new list. We are just setting the `list` variable to point to the existing brackets (which is set to watch currentListProvider in the previous line). In contrast, my version makes a NEW list based on brackets (using the `from` constructor of the `List` class). In other words, `final List list = brackets;` assigns a reference to the original list, whereas `final List list = List.from(brackets);` creates a new list with the same elements as the original list. – Plonetheus Mar 02 '23 at 16:23