tween_sequence.dart 5.38 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'tween.dart';

7 8
export 'tween.dart' show Animatable;

9
// Examples can assume:
10
// late AnimationController myAnimationController;
11

12 13
/// Enables creating an [Animation] whose value is defined by a sequence of
/// [Tween]s.
14
///
15 16 17
/// Each [TweenSequenceItem] has a weight that defines its percentage of the
/// animation's duration. Each tween defines the animation's value during the
/// interval indicated by its weight.
18
///
19
/// {@tool snippet}
20 21 22
/// This example defines an animation that uses an easing curve to interpolate
/// between 5.0 and 10.0 during the first 40% of the animation, remains at 10.0
/// for the next 20%, and then returns to 5.0 for the final 40%.
23
///
24
/// ```dart
25
/// final Animation<double> animation = TweenSequence<double>(
26
///   <TweenSequenceItem<double>>[
27 28 29
///     TweenSequenceItem<double>(
///       tween: Tween<double>(begin: 5.0, end: 10.0)
///         .chain(CurveTween(curve: Curves.ease)),
30 31
///       weight: 40.0,
///     ),
32 33
///     TweenSequenceItem<double>(
///       tween: ConstantTween<double>(10.0),
34 35
///       weight: 20.0,
///     ),
36 37 38
///     TweenSequenceItem<double>(
///       tween: Tween<double>(begin: 10.0, end: 5.0)
///         .chain(CurveTween(curve: Curves.ease)),
39 40 41 42
///       weight: 40.0,
///     ),
///   ],
/// ).animate(myAnimationController);
43
/// ```
44
/// {@end-tool}
45 46 47
class TweenSequence<T> extends Animatable<T> {
  /// Construct a TweenSequence.
  ///
48
  /// The [items] parameter must be a list of one or more [TweenSequenceItem]s.
49
  ///
50
  /// There's a small cost associated with building a [TweenSequence] so it's
51 52
  /// best to reuse one, rather than rebuilding it on every frame, when that's
  /// possible.
53 54 55
  TweenSequence(List<TweenSequenceItem<T>> items)
      : assert(items != null),
        assert(items.isNotEmpty) {
56 57 58
    _items.addAll(items);

    double totalWeight = 0.0;
59
    for (final TweenSequenceItem<T> item in _items) {
60
      totalWeight += item.weight;
61
    }
62 63 64 65 66
    assert(totalWeight > 0.0);

    double start = 0.0;
    for (int i = 0; i < _items.length; i += 1) {
      final double end = i == _items.length - 1 ? 1.0 : start + _items[i].weight / totalWeight;
67
      _intervals.add(_Interval(start, end));
68 69 70 71 72 73 74 75 76 77
      start = end;
    }
  }

  final List<TweenSequenceItem<T>> _items = <TweenSequenceItem<T>>[];
  final List<_Interval> _intervals = <_Interval>[];

  T _evaluateAt(double t, int index) {
    final TweenSequenceItem<T> element = _items[index];
    final double tInterval = _intervals[index].value(t);
78
    return element.tween.transform(tInterval);
79 80 81
  }

  @override
82
  T transform(double t) {
83
    assert(t >= 0.0 && t <= 1.0);
84
    if (t == 1.0) {
85
      return _evaluateAt(t, _items.length - 1);
86
    }
87
    for (int index = 0; index < _items.length; index++) {
88
      if (_intervals[index].contains(t)) {
89
        return _evaluateAt(t, index);
90
      }
91 92
    }
    // Should be unreachable.
93
    throw StateError('TweenSequence.evaluate() could not find an interval for $t');
94
  }
95 96 97

  @override
  String toString() => 'TweenSequence(${_items.length} items)';
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/// Enables creating a flipped [Animation] whose value is defined by a sequence
/// of [Tween]s.
///
/// This creates a [TweenSequence] that evaluates to a result that flips the
/// tween both horizontally and vertically.
///
/// This tween sequence assumes that the evaluated result has to be a double
/// between 0.0 and 1.0.
class FlippedTweenSequence extends TweenSequence<double> {
  /// Creates a flipped [TweenSequence].
  ///
  /// The [items] parameter must be a list of one or more [TweenSequenceItem]s.
  ///
  /// There's a small cost associated with building a `TweenSequence` so it's
  /// best to reuse one, rather than rebuilding it on every frame, when that's
  /// possible.
116 117
  FlippedTweenSequence(super.items)
    : assert(items != null);
118 119 120 121 122

  @override
  double transform(double t) => 1 - super.transform(1 - t);
}

123 124 125 126 127 128
/// A simple holder for one element of a [TweenSequence].
class TweenSequenceItem<T> {
  /// Construct a TweenSequenceItem.
  ///
  /// The [tween] must not be null and [weight] must be greater than 0.0.
  const TweenSequenceItem({
129 130
    required this.tween,
    required this.weight,
131 132 133
  }) : assert(tween != null),
       assert(weight != null),
       assert(weight > 0.0);
134 135 136 137 138

  /// Defines the value of the [TweenSequence] for the interval within the
  /// animation's duration indicated by [weight] and this item's position
  /// in the list of items.
  ///
139
  /// {@tool snippet}
140
  ///
141 142
  /// The value of this item can be "curved" by chaining it to a [CurveTween].
  /// For example to create a tween that eases from 0.0 to 10.0:
143 144 145 146
  ///
  /// ```dart
  /// Tween<double>(begin: 0.0, end: 10.0)
  ///   .chain(CurveTween(curve: Curves.ease))
147
  /// ```
148
  /// {@end-tool}
149 150
  final Animatable<T> tween;

151
  /// An arbitrary value that indicates the relative percentage of a
152 153
  /// [TweenSequence] animation's duration when [tween] will be used.
  ///
154 155
  /// The percentage for an individual item is the item's weight divided by the
  /// sum of all of the items' weights.
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  final double weight;
}

class _Interval {
  const _Interval(this.start, this.end) : assert(end > start);

  final double start;
  final double end;

  bool contains(double t) => t >= start && t < end;

  double value(double t) => (t - start) / (end - start);

  @override
  String toString() => '<$start, $end>';
}