|
| 1 | +import 'package:flutter/animation.dart'; |
| 2 | + |
| 3 | +/// An animation that clamps the value of another animation within a specified range. |
| 4 | +/// |
| 5 | +/// This animation proxies the parent animation but enforces a minimum and a maximum |
| 6 | +/// limit on its value. If the parent animation produces a value outside of this |
| 7 | +/// range, it is clamped to the nearest boundary defined by [min] and [max]. |
| 8 | +/// |
| 9 | +/// The [min] value should be less than the [max] value. |
| 10 | +/// |
| 11 | +/// Example usage: |
| 12 | +/// ```dart |
| 13 | +/// final ClampedAnimation clampedAnimation = ClampedAnimation( |
| 14 | +/// parent: parent, |
| 15 | +/// min: 0.0, |
| 16 | +/// max: 1.0, |
| 17 | +/// ); |
| 18 | +/// ``` |
| 19 | +/// Here `clampedAnimation.value` will always be between 0.0 and 1.0, inclusive. |
| 20 | +class ClampedAnimation extends Animation<double> |
| 21 | + with AnimationWithParentMixin<double> { |
| 22 | + /// Creates a clamped animation with an invariant range. |
| 23 | + /// |
| 24 | + /// The [parent] animation is the source of values for this animation. |
| 25 | + /// The [min] and [max] parameters specify the range within which the |
| 26 | + /// values of the parent animation should be clamped. |
| 27 | + /// The constructor asserts that [min] is less than [max]. |
| 28 | + const ClampedAnimation({ |
| 29 | + required this.parent, |
| 30 | + required this.min, |
| 31 | + required this.max, |
| 32 | + }) : assert(min < max, 'The min value must be less than the max value.'); |
| 33 | + |
| 34 | + /// The animation that this clamped animation is based on. |
| 35 | + @override |
| 36 | + final Animation<double> parent; |
| 37 | + |
| 38 | + /// The minimum value of the clamped range. |
| 39 | + final double min; |
| 40 | + |
| 41 | + /// The maximum value of the clamped range. |
| 42 | + final double max; |
| 43 | + |
| 44 | + /// Gets the current value of the parent animation clamped to the range [min] to [max]. |
| 45 | + /// |
| 46 | + /// This method overrides the getter for `value` from the parent class and applies |
| 47 | + /// the clamping logic to the current value of the [parent] animation. |
| 48 | + @override |
| 49 | + double get value => parent.value.clamp(min, max); |
| 50 | + |
| 51 | + @override |
| 52 | + String toString() => '$parent(min: $min, max: $max)'; |
| 53 | +} |
0 commit comments