Skip to content

Instantly share code, notes, and snippets.

@caseycrogers
Created October 7, 2021 19:46
Show Gist options
  • Save caseycrogers/82556634dd0ef6dff4deda2b48b23e7b to your computer and use it in GitHub Desktop.
Save caseycrogers/82556634dd0ef6dff4deda2b48b23e7b to your computer and use it in GitHub Desktop.
import 'package:flutter/cupertino.dart';
extension ValueNotifierExtension<T> on ValueNotifier<T> {
ValueNotifier<R> map<R>(
R Function(T value) mapper,
T Function(R value) backMapper,
) {
final ValueNotifier<R> proxyNotifier = ValueNotifier(mapper(value));
proxyNotifier.addListener(() {
value = backMapper(proxyNotifier.value);
});
void onValueChanged() {
proxyNotifier.value = mapper(value);
}
addListener(onValueChanged);
return proxyNotifier;
}
ValueNotifier<R> expand<R>(ValueNotifier<R> Function(T value) mapper) {
ValueNotifier<R>? notifier;
late final ValueNotifier<R> proxyNotifier = ValueNotifier(notifier!.value);
void onInnerValueChanged() {
proxyNotifier.value = notifier!.value;
}
void onValueChanged() {
notifier?.removeListener(onInnerValueChanged);
notifier = mapper(value);
notifier!.addListener(onInnerValueChanged);
}
// Call once to initialize.
onValueChanged();
addListener(onValueChanged);
return proxyNotifier;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment