Skip to content

Ref.listen weak flag run on hot reload #4376

@robpot95

Description

@robpot95

Describe the bug
Ref.listen weak flag true on hot reload cause it awake the provider it listen to even tho no changes been made

To Reproduce

class Item {
  const Item({this.id = 0, this.word = ''});

  final int id;
  final String word;
}

const items = <Item>[
  Item(id: 1, word: "Honey"),
  Item(id: 2, word: "Sweet Potato"),
  Item(id: 3, word: "Bird is the word"),
];

@riverpod
class A extends _$A {
  @override
  FutureOr<List<Item>> build() async {
    final response = await Future.delayed(
      const Duration(seconds: 1),
      () => items,
    );

    if (!ref.mounted) {
      return <Item>[];
    }

    for (final item in response) {
      ref.listen(bProvider(item.id), weak: true, (_, next) {
        next.whenData((updatedItem) async {
          final previousState = await future;
          state = AsyncData(<Item>[
            for (final oldItem in previousState)
              if (oldItem.id == updatedItem.id) updatedItem else oldItem,
          ]);
        });
      });
    }

    return response;
  }
}

@riverpod
class B extends _$B {
  @override
  FutureOr<Item> build(int id) async {
    print("Fetch item: $id");
    return Future.delayed(
      const Duration(seconds: 1),
      () =>
          items.firstWhere((item) => item.id == id, orElse: () => const Item()),
    );
  }

  Future<void> addWord(String word) async {
    await Future.delayed(const Duration(seconds: 1));
    state = AsyncData(Item(id: id, word: word));
  }
}

output:

flutter: Fetch item: 1
flutter: Fetch item: 2
flutter: Fetch item: 3

Expected behavior
B should only wake up when changes are made

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions