Created
April 11, 2021 07:43
-
-
Save hacker1024/e5653a4bd65ab5e845f8e78baa314eb7 to your computer and use it in GitHub Desktop.
A Flutter Animation implementation that wraps a mutable value.
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/widgets.dart'; | |
abstract class ValueAnimation<T> extends Animation<T> | |
with | |
AnimationEagerListenerMixin, | |
AnimationLocalListenersMixin, | |
AnimationLocalStatusListenersMixin { | |
T _value; | |
@override | |
T get value => _value; | |
set value(T value) { | |
if (value == _value) return; | |
final status = calculateStatus(_value, value); | |
_value = value; | |
notifyListeners(); | |
if (status == _status) return; | |
_status = status; | |
notifyStatusListeners(status); | |
} | |
AnimationStatus _status; | |
@override | |
AnimationStatus get status => _status; | |
ValueAnimation(this._value, this._status); | |
@protected | |
AnimationStatus calculateStatus(T oldValue, T newValue); | |
} | |
class DoubleValueAnimation extends ValueAnimation<double> { | |
DoubleValueAnimation(double value, AnimationStatus status) | |
: assert(value >= 0 && value <= 1), | |
assert(status != AnimationStatus.dismissed || value == 0), | |
assert(status != AnimationStatus.completed || value == 1), | |
super(value, status); | |
DoubleValueAnimation.beginning() : this(0, AnimationStatus.dismissed); | |
DoubleValueAnimation.end() : this(1, AnimationStatus.completed); | |
@override | |
set value(double value) { | |
assert(value >= 0 && value <= 1); | |
super.value = value; | |
} | |
@override | |
AnimationStatus calculateStatus(double oldValue, double newValue) { | |
assert(oldValue != newValue, | |
'The status should not be calculated for equal values!'); | |
if (newValue == 0) { | |
return AnimationStatus.dismissed; | |
} | |
if (newValue == 1) { | |
return AnimationStatus.completed; | |
} | |
if (newValue > oldValue) { | |
return AnimationStatus.forward; | |
} else { | |
return AnimationStatus.reverse; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment