Last active
July 19, 2021 18:43
-
-
Save renancaraujo/2d8618e82e9d6b90dd559f78afe7635c to your computer and use it in GitHub Desktop.
computed_value_notifier.dart
This file contains hidden or 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/foundation.dart'; | |
typedef ValueComputation<T, O> = T Function(O value); | |
class ComputedValueNotifier<T> extends ValueNotifier<T> { | |
final Listenable _parent; | |
final ValueGetter<T> _compute; | |
factory ComputedValueNotifier.fromListenable( | |
Listenable notifier, | |
ValueGetter<T> callback, | |
) { | |
return ComputedValueNotifier._(notifier, callback, callback()); | |
} | |
static ComputedValueNotifier<T> fromValueNotifier<T, O>( | |
ValueNotifier<O> parent, | |
ValueComputation<T, O> compute, | |
) { | |
return _ComputedValueNotifierFromValueNotifiers(parent, compute); | |
} | |
ComputedValueNotifier._( | |
this._parent, | |
this._compute, | |
T initial, | |
) : super(initial) { | |
_parent.addListener(_internalListener); | |
} | |
void _internalListener() { | |
value = _compute(); | |
} | |
@override | |
void dispose() { | |
_parent.removeListener(_internalListener); | |
super.dispose(); | |
} | |
} | |
class _ComputedValueNotifierFromValueNotifiers<T, O> extends ValueNotifier<T> | |
implements ComputedValueNotifier<T> { | |
@override | |
final ValueNotifier<O> _parent; | |
@override | |
final ValueGetter<T> _compute; | |
factory _ComputedValueNotifierFromValueNotifiers( | |
ValueNotifier<O> parent, | |
ValueComputation<T, O> compute, | |
) { | |
return _ComputedValueNotifierFromValueNotifiers._( | |
parent, | |
() => compute(parent.value), | |
compute(parent.value), | |
); | |
} | |
_ComputedValueNotifierFromValueNotifiers._( | |
this._parent, | |
this._compute, | |
T initial, | |
) : super(initial) { | |
_parent.addListener(_internalListener); | |
} | |
@override | |
void _internalListener() { | |
value = _compute(); | |
} | |
@override | |
void dispose() { | |
_parent.removeListener(_internalListener); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment