Skip to content

Instantly share code, notes, and snippets.

@xsahil03x
Created December 15, 2021 12:21
Show Gist options
  • Save xsahil03x/18d53454b2c996a8a23b5d40a4d36c34 to your computer and use it in GitHub Desktop.
Save xsahil03x/18d53454b2c996a8a23b5d40a4d36c34 to your computer and use it in GitHub Desktop.
SelectValueNotifier
class _SelectValueNotifier<R, T> extends ValueNotifier<R> {
_SelectValueNotifier(this.source, this.selector)
: super(selector(source.value)) {
source.addListener(_sourceListener);
}
final ValueNotifier<T> source;
final R Function(T value) selector;
void _sourceListener() => value = selector(source.value);
@override
void dispose() {
source.removeListener(_sourceListener);
super.dispose();
}
}
extension SelectValueNotifier<T> on ValueNotifier<T> {
ValueNotifier<R> select<R>(R Function(T value) selector) =>
_SelectValueNotifier<R, T>(this, selector);
}
@xsahil03x
Copy link
Author

Usage:

final car = Car(id: 1, name: 'Honda');
final carNotifier = ValueNotifier(car);
final carNameNotifier = carNotifier.select((car) => car.name);

carNameNotifier.addListener(() {
  print('Car name: ${carNameNotifier.value}');
});

OR

ValueListenableBuilder(
  valueListenable: carNotifier.select((car) => car.name),
  builder: (BuildContext context, value, Widget? child) {
     return Text('Car name: $value);
  }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment