tween.dart 16.3 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
// @dart = 2.8

7
import 'dart:ui' show Color, Size, Rect;
8

9 10
import 'package:flutter/foundation.dart';

11 12
import 'animation.dart';
import 'animations.dart';
13
import 'curves.dart';
14

15 16
// Examples can assume:
// Animation<Offset> _animation;
17
// AnimationController _controller;
18

19 20 21 22 23
/// An object that can produce a value of type `T` given an [Animation<double>]
/// as input.
///
/// Typically, the values of the input animation are nominally in the range 0.0
/// to 1.0. In principle, however, any value could be provided.
24 25
///
/// The main subclass of [Animatable] is [Tween].
26
abstract class Animatable<T> {
27 28
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
29
  const Animatable();
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  /// Returns the value of the object at point `t`.
  ///
  /// The value of `t` is nominally a fraction in the range 0.0 to 1.0, though
  /// in practice it may extend outside this range.
  ///
  /// See also:
  ///
  ///  * [evaluate], which is a shorthand for applying [transform] to the value
  ///    of an [Animation].
  ///  * [Curve.transform], a similar method for easing curves.
  T transform(double t);

  /// The current value of this object for the given [Animation].
  ///
  /// This function is implemented by deferring to [transform]. Subclasses that
  /// want to provide custom behavior should override [transform], not
  /// [evaluate].
  ///
  /// See also:
  ///
  ///  * [transform], which is similar but takes a `t` value directly instead of
  ///    an [Animation].
  ///  * [animate], which creates an [Animation] out of this object, continually
  ///    applying [evaluate].
  T evaluate(Animation<double> animation) => transform(animation.value);
56

57
  /// Returns a new [Animation] that is driven by the given animation but that
58
  /// takes on values determined by this object.
59 60 61 62 63 64 65 66
  ///
  /// Essentially this returns an [Animation] that automatically applies the
  /// [evaluate] method to the parent's value.
  ///
  /// See also:
  ///
  ///  * [AnimationController.drive], which does the same thing from the
  ///    opposite starting point.
67
  Animation<T> animate(Animation<double> parent) {
68
    return _AnimatedEvaluation<T>(parent, this);
69
  }
70

71
  /// Returns a new [Animatable] whose value is determined by first evaluating
72
  /// the given parent and then evaluating this object.
73 74
  ///
  /// This allows [Tween]s to be chained before obtaining an [Animation].
75
  Animatable<T> chain(Animatable<double> parent) {
76
    return _ChainedEvaluation<T>(parent, this);
77
  }
78 79
}

80
class _AnimatedEvaluation<T> extends Animation<T> with AnimationWithParentMixin<double> {
81
  _AnimatedEvaluation(this.parent, this._evaluatable);
82

83
  @override
84
  final Animation<double> parent;
85

86
  final Animatable<T> _evaluatable;
87

88
  @override
89
  T get value => _evaluatable.evaluate(parent);
90 91 92

  @override
  String toString() {
93
    return '$parent\u27A9$_evaluatable\u27A9$value';
94 95 96 97 98 99
  }

  @override
  String toStringDetails() {
    return '${super.toStringDetails()} $_evaluatable';
  }
100 101
}

102
class _ChainedEvaluation<T> extends Animatable<T> {
103 104
  _ChainedEvaluation(this._parent, this._evaluatable);

105 106
  final Animatable<double> _parent;
  final Animatable<T> _evaluatable;
107

108
  @override
109 110
  T transform(double t) {
    return _evaluatable.transform(_parent.transform(t));
111
  }
112 113 114 115 116

  @override
  String toString() {
    return '$_parent\u27A9$_evaluatable';
  }
117 118
}

119
/// A linear interpolation between a beginning and ending value.
120 121 122
///
/// [Tween] is useful if you want to interpolate across a range.
///
123
/// To use a [Tween] object with an animation, call the [Tween] object's
124
/// [animate] method and pass it the [Animation] object that you want to
125
/// modify.
126
///
127
/// You can chain [Tween] objects together using the [chain] method, so that a
128
/// single [Animation] object is configured by multiple [Tween] objects called
129
/// in succession. This is different than calling the [animate] method twice,
130
/// which results in two separate [Animation] objects, each configured with a
131
/// single [Tween].
132
///
133
/// {@tool snippet}
134 135 136
///
/// Suppose `_controller` is an [AnimationController], and we want to create an
/// [Animation<Offset>] that is controlled by that controller, and save it in
137 138 139 140 141 142 143 144 145 146
/// `_animation`. Here are two possible ways of expressing this:
///
/// ```dart
/// _animation = _controller.drive(
///   Tween<Offset>(
///     begin: const Offset(100.0, 50.0),
///     end: const Offset(200.0, 300.0),
///   ),
/// );
/// ```
147
/// {@end-tool}
148
/// {@tool snippet}
149 150
///
/// ```dart
151
/// _animation = Tween<Offset>(
152 153
///   begin: const Offset(100.0, 50.0),
///   end: const Offset(200.0, 300.0),
154
/// ).animate(_controller);
155
/// ```
156
/// {@end-tool}
157
///
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
/// In both cases, the `_animation` variable holds an object that, over the
/// lifetime of the `_controller`'s animation, returns a value
/// (`_animation.value`) that depicts a point along the line between the two
/// offsets above. If we used a [MaterialPointArcTween] instead of a
/// [Tween<Offset>] in the code above, the points would follow a pleasing curve
/// instead of a straight line, with no other changes necessary.
///
/// ## Performance optimizations
///
/// Tweens are mutable; specifically, their [begin] and [end] values can be
/// changed at runtime. An object created with [Animation.drive] using a [Tween]
/// will immediately honor changes to that underlying [Tween] (though the
/// listeners will only be triggered if the [Animation] is actively animating).
/// This can be used to change an animation on the fly without having to
/// recreate all the objects in the chain from the [AnimationController] to the
/// final [Tween].
///
175
/// If a [Tween]'s values are never changed, however, a further optimization can
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
/// be applied: the object can be stored in a `static final` variable, so that
/// the exact same instance is used whenever the [Tween] is needed. This is
/// preferable to creating an identical [Tween] afresh each time a [State.build]
/// method is called, for example.
///
/// ## Types with special considerations
///
/// Classes with [lerp] static methods typically have corresponding dedicated
/// [Tween] subclasses that call that method. For example, [ColorTween] uses
/// [Color.lerp] to implement the [ColorTween.lerp] method.
///
/// Types that define `+` and `-` operators to combine values (`T + T → T` and
/// `T - T → T`) and an `*` operator to scale by multiplying with a double (`T *
/// double → T`) can be directly used with `Tween<T>`.
///
/// This does not extend to any type with `+`, `-`, and `*` operators. In
/// particular, [int] does not satisfy this precise contract (`int * double`
/// actually returns [num], not [int]). There are therefore two specific classes
/// that can be used to interpolate integers:
///
///  * [IntTween], which is an approximation of a linear interpolation (using
///    [double.round]).
///  * [StepTween], which uses [double.floor] to ensure that the result is
///    never greater than it would be using if a `Tween<double>`.
///
/// The relevant operators on [Size] also don't fulfill this contract, so
/// [SizeTween] uses [Size.lerp].
///
/// In addition, some of the types that _do_ have suitable `+`, `-`, and `*`
/// operators still have dedicated [Tween] subclasses that perform the
/// interpolation in a more specialized manner. One such class is
/// [MaterialPointArcTween], which is mentioned above. The [AlignmentTween], and
/// [AlignmentGeometryTween], and [FractionalOffsetTween] are another group of
/// [Tween]s that use dedicated `lerp` methods instead of merely relying on the
/// operators (in particular, this allows them to handle null values in a more
/// useful manner).
212
class Tween<T extends dynamic> extends Animatable<T> {
213 214
  /// Creates a tween.
  ///
215 216 217
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
218
  Tween({ this.begin, this.end });
219 220

  /// The value this variable has at the beginning of the animation.
221
  ///
222 223
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
224 225 226
  T begin;

  /// The value this variable has at the end of the animation.
227
  ///
228 229
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
230 231 232
  T end;

  /// Returns the value this variable has at the given animation clock value.
233
  ///
234 235 236
  /// The default implementation of this method uses the [+], [-], and [*]
  /// operators on `T`. The [begin] and [end] properties must therefore be
  /// non-null by the time this method is called.
237
  @protected
238 239 240
  T lerp(double t) {
    assert(begin != null);
    assert(end != null);
241
    return begin + (end - begin) * t as T;
242
  }
243

244
  /// Returns the interpolated value for the current value of the given animation.
245
  ///
246 247 248
  /// This method returns `begin` and `end` when the animation values are 0.0 or
  /// 1.0, respectively.
  ///
249 250 251
  /// This function is implemented by deferring to [lerp]. Subclasses that want
  /// to provide custom behavior should override [lerp], not [transform] (nor
  /// [evaluate]).
252 253 254 255
  ///
  /// See the constructor for details about whether the [begin] and [end]
  /// properties may be null when this is called. It varies from subclass to
  /// subclass.
256
  @override
257
  T transform(double t) {
258 259 260 261 262 263
    if (t == 0.0)
      return begin;
    if (t == 1.0)
      return end;
    return lerp(t);
  }
264

265
  @override
266
  String toString() => '${objectRuntimeType(this, 'Animatable')}($begin \u2192 $end)';
267 268
}

269 270 271
/// A [Tween] that evaluates its [parent] in reverse.
class ReverseTween<T> extends Tween<T> {
  /// Construct a [Tween] that evaluates its [parent] in reverse.
272 273 274
  ReverseTween(this.parent)
    : assert(parent != null),
      super(begin: parent.end, end: parent.begin);
275 276 277 278 279 280 281 282 283 284 285 286

  /// This tween's value is the same as the parent's value evaluated in reverse.
  ///
  /// This tween's [begin] is the parent's [end] and its [end] is the parent's
  /// [begin]. The [lerp] method returns `parent.lerp(1.0 - t)` and its
  /// [evaluate] method is similar.
  final Tween<T> parent;

  @override
  T lerp(double t) => parent.lerp(1.0 - t);
}

287
/// An interpolation between two colors.
288
///
289 290 291 292
/// This class specializes the interpolation of [Tween<Color>] to use
/// [Color.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
293
class ColorTween extends Tween<Color> {
294
  /// Creates a [Color] tween.
295
  ///
296
  /// The [begin] and [end] properties may be null; the null value
297 298 299 300 301 302
  /// is treated as transparent.
  ///
  /// We recommend that you do not pass [Colors.transparent] as [begin]
  /// or [end] if you want the effect of fading in or out of transparent.
  /// Instead prefer null. [Colors.transparent] refers to black transparent and
  /// thus will fade out of or into black which is likely unwanted.
303 304
  ColorTween({ Color begin, Color end }) : super(begin: begin, end: end);

305
  /// Returns the value this variable has at the given animation clock value.
306
  @override
307 308 309
  Color lerp(double t) => Color.lerp(begin, end, t);
}

310
/// An interpolation between two sizes.
311
///
312 313 314 315
/// This class specializes the interpolation of [Tween<Size>] to use
/// [Size.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
316
class SizeTween extends Tween<Size> {
317
  /// Creates a [Size] tween.
318
  ///
319 320
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty size.
321 322
  SizeTween({ Size begin, Size end }) : super(begin: begin, end: end);

323
  /// Returns the value this variable has at the given animation clock value.
324
  @override
325 326 327
  Size lerp(double t) => Size.lerp(begin, end, t);
}

328
/// An interpolation between two rectangles.
329
///
330 331 332 333
/// This class specializes the interpolation of [Tween<Rect>] to use
/// [Rect.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
334
class RectTween extends Tween<Rect> {
335
  /// Creates a [Rect] tween.
336
  ///
337 338
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty rect at the top left corner.
339 340
  RectTween({ Rect begin, Rect end }) : super(begin: begin, end: end);

341
  /// Returns the value this variable has at the given animation clock value.
342
  @override
343 344 345
  Rect lerp(double t) => Rect.lerp(begin, end, t);
}

346
/// An interpolation between two integers that rounds.
347
///
348
/// This class specializes the interpolation of [Tween<int>] to be
349 350 351 352
/// appropriate for integers by interpolating between the given begin
/// and end values and then rounding the result to the nearest
/// integer.
///
353 354 355 356
/// This is the closest approximation to a linear tween that is possible with an
/// integer. Compare to [StepTween] and [Tween<double>].
///
/// See [Tween] for a discussion on how to use interpolation objects.
357
class IntTween extends Tween<int> {
358 359
  /// Creates an int tween.
  ///
360 361 362
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
363 364 365 366
  IntTween({ int begin, int end }) : super(begin: begin, end: end);

  // The inherited lerp() function doesn't work with ints because it multiplies
  // the begin and end types by a double, and int * double returns a double.
367
  @override
368 369
  int lerp(double t) => (begin + (end - begin) * t).round();
}
370

371 372
/// An interpolation between two integers that floors.
///
373
/// This class specializes the interpolation of [Tween<int>] to be
374
/// appropriate for integers by interpolating between the given begin
375
/// and end values and then using [double.floor] to return the current
376 377 378 379
/// integer component, dropping the fractional component.
///
/// This results in a value that is never greater than the equivalent
/// value from a linear double interpolation. Compare to [IntTween].
380 381
///
/// See [Tween] for a discussion on how to use interpolation objects.
382
class StepTween extends Tween<int> {
383
  /// Creates an [int] tween that floors.
384
  ///
385 386 387
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
388 389 390 391
  StepTween({ int begin, int end }) : super(begin: begin, end: end);

  // The inherited lerp() function doesn't work with ints because it multiplies
  // the begin and end types by a double, and int * double returns a double.
392
  @override
393 394 395
  int lerp(double t) => (begin + (end - begin) * t).floor();
}

396 397 398 399 400
/// A tween with a constant value.
class ConstantTween<T> extends Tween<T> {
  /// Create a tween whose [begin] and [end] values equal [value].
  ConstantTween(T value) : super(begin: value, end: value);

Dan Field's avatar
Dan Field committed
401
  /// This tween doesn't interpolate, it always returns the same value.
402 403 404 405
  @override
  T lerp(double t) => begin;

  @override
406
  String toString() => '${objectRuntimeType(this, 'ReverseTween')}(value: $begin)';
407 408
}

409 410 411 412 413
/// Transforms the value of the given animation by the given curve.
///
/// This class differs from [CurvedAnimation] in that [CurvedAnimation] applies
/// a curve to an existing [Animation] object whereas [CurveTween] can be
/// chained with another [Tween] prior to receiving the underlying [Animation].
414 415 416 417
/// ([CurvedAnimation] also has the additional ability of having different
/// curves when the animation is going forward vs when it is going backward,
/// which can be useful in some scenarios.)
///
418
/// {@tool snippet}
419 420 421 422 423
///
/// The following code snippet shows how you can apply a curve to a linear
/// animation produced by an [AnimationController] `controller`:
///
/// ```dart
424
/// final Animation<double> animation = _controller.drive(
425 426 427
///   CurveTween(curve: Curves.ease),
/// );
/// ```
428
/// {@end-tool}
429 430 431 432 433 434
///
/// See also:
///
///  * [CurvedAnimation], for an alternative way of expressing the sample above.
///  * [AnimationController], for examples of creating and disposing of an
///    [AnimationController].
435
class CurveTween extends Animatable<double> {
436 437 438
  /// Creates a curve tween.
  ///
  /// The [curve] argument must not be null.
439 440
  CurveTween({ @required this.curve })
    : assert(curve != null);
441

442
  /// The curve to use when transforming the value of the animation.
443 444
  Curve curve;

445
  @override
446
  double transform(double t) {
447 448 449 450 451 452
    if (t == 0.0 || t == 1.0) {
      assert(curve.transform(t).round() == t);
      return t;
    }
    return curve.transform(t);
  }
453 454

  @override
455
  String toString() => '${objectRuntimeType(this, 'CurveTween')}(curve: $curve)';
456
}