Skip to content

Commit

Permalink
Add method
Browse files Browse the repository at this point in the history
  • Loading branch information
lukehutch committed Jun 12, 2023
1 parent 42687ea commit d83f9eb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ Now whenever `counter.value` changes (here using `counter.value++` in the `onPre

That's all there is to it!

## Notifying listeners of deeper changes

If you try to wrap a collection or object in a `ValueNotifier`, e.g. to track a set of values using `ValueNotifier<Set<T>>`, then modifying fields, or adding or removing values from the collection or object will not notify the listeners of the `ValueNotifier` that the value has changed (because the value itself has not changed). In this case you can call the extension method `notifyChanged()` to manually call the listeners. For example:

```dart
final tags = ValueNotifier(<String>{});
void addOrRemoveTag(String tag, bool add) {
if ((add && tags.value.add(tag)) || (!add && tags.value.remove(tag))) {
tags.notifyChanged();
}
}
```

## The code

The `flutter_reactive_value` mechanism is extremely simple. [See the code here.](https://github.com/lukehutch/flutter_reactive_value/blob/main/lib/src/reactive_value_notifier.dart)
Expand Down
13 changes: 13 additions & 0 deletions lib/src/reactive_value_notifier.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ class _ListenerWrapper<T> {
void Function()? listener;
}

/// Extend [ValueNotifier] so that [Element] objects in the build tree can
/// respond to changes in the value.
extension ReactiveValueNotifier<T> on ValueNotifier<T> {
/// Fetch the [value] of this [ValueNotifier], and subscribe the element
/// that is currently being built (the [context]) to any changes in the
/// value.
T reactiveValue(BuildContext context) {
final elementRef = WeakReference(context as Element);
// Can't refer to listener while it is being declared, so need to add
Expand All @@ -29,4 +34,12 @@ extension ReactiveValueNotifier<T> on ValueNotifier<T> {
addListener(listenerWrapper.listener!);
return value;
}

/// Use this method to notify listeners of deeper changes, e.g. when a value
/// is added to or removed from a set which is stored in the value of a
/// `ValueNotifier<Set<T>>`.
void notifyChanged() {
// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
notifyListeners();
}
}

0 comments on commit d83f9eb

Please sign in to comment.