Created
October 7, 2021 19:46
-
-
Save caseycrogers/82556634dd0ef6dff4deda2b48b23e7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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