tween_sequence.dart 5.24 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
  TweenSequence(List<TweenSequenceItem<T>> items)
54
      : assert(items.isNotEmpty) {
55 56 57
    _items.addAll(items);

    double totalWeight = 0.0;
58
    for (final TweenSequenceItem<T> item in _items) {
59
      totalWeight += item.weight;
60
    }
61 62 63 64 65
    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;
66
      _intervals.add(_Interval(start, end));
67 68 69 70 71 72 73 74 75 76
      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);
77
    return element.tween.transform(tInterval);
78 79 80
  }

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

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

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
/// 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.
115
  FlippedTweenSequence(super.items);
116 117 118 119 120

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

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

  /// 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.
  ///
135
  /// {@tool snippet}
136
  ///
137 138
  /// 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:
139 140 141 142
  ///
  /// ```dart
  /// Tween<double>(begin: 0.0, end: 10.0)
  ///   .chain(CurveTween(curve: Curves.ease))
143
  /// ```
144
  /// {@end-tool}
145 146
  final Animatable<T> tween;

147
  /// An arbitrary value that indicates the relative percentage of a
148 149
  /// [TweenSequence] animation's duration when [tween] will be used.
  ///
150 151
  /// The percentage for an individual item is the item's weight divided by the
  /// sum of all of the items' weights.
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  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>';
}