tween.dart 19.6 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
import 'dart:ui' show Color, Size, Rect;
6

7 8
import 'package:flutter/foundation.dart';

9 10
import 'animation.dart';
import 'animations.dart';
11
import 'curves.dart';
12

13
// Examples can assume:
14 15
// late Animation<Offset> _animation;
// late AnimationController _controller;
16

17 18 19 20 21
/// 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.
22 23
///
/// The main subclass of [Animatable] is [Tween].
24
abstract class Animatable<T> {
25 26
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
27
  const Animatable();
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /// 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);
54

55
  /// Returns a new [Animation] that is driven by the given animation but that
56
  /// takes on values determined by this object.
57 58 59 60 61 62 63 64
  ///
  /// 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.
65
  Animation<T> animate(Animation<double> parent) {
66
    return _AnimatedEvaluation<T>(parent, this);
67
  }
68

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

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

81
  @override
82
  final Animation<double> parent;
83

84
  final Animatable<T> _evaluatable;
85

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

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

  @override
  String toStringDetails() {
    return '${super.toStringDetails()} $_evaluatable';
  }
98 99
}

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

103 104
  final Animatable<double> _parent;
  final Animatable<T> _evaluatable;
105

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

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

117
/// A linear interpolation between a beginning and ending value.
118 119 120
///
/// [Tween] is useful if you want to interpolate across a range.
///
121
/// To use a [Tween] object with an animation, call the [Tween] object's
122
/// [animate] method and pass it the [Animation] object that you want to
123
/// modify.
124
///
125
/// You can chain [Tween] objects together using the [chain] method, so that a
126
/// single [Animation] object is configured by multiple [Tween] objects called
127
/// in succession. This is different than calling the [animate] method twice,
128
/// which results in two separate [Animation] objects, each configured with a
129
/// single [Tween].
130
///
131
/// {@tool snippet}
132 133 134
///
/// Suppose `_controller` is an [AnimationController], and we want to create an
/// [Animation<Offset>] that is controlled by that controller, and save it in
135 136 137 138 139 140 141 142 143 144
/// `_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),
///   ),
/// );
/// ```
145
/// {@end-tool}
146
/// {@tool snippet}
147 148
///
/// ```dart
149
/// _animation = Tween<Offset>(
150 151
///   begin: const Offset(100.0, 50.0),
///   end: const Offset(200.0, 300.0),
152
/// ).animate(_controller);
153
/// ```
154
/// {@end-tool}
155
///
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
/// 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].
///
173
/// If a [Tween]'s values are never changed, however, a further optimization can
174 175 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
/// 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).
210 211 212 213 214 215 216 217 218 219 220 221 222 223
///
/// ## Nullability
///
/// The [begin] and [end] fields are nullable; a [Tween] does not have to
/// have non-null values specified when it is created.
///
/// If `T` is nullable, then [lerp] and [transform] may return null.
/// This is typically seen in the case where [begin] is null and `t`
/// is 0.0, or [end] is null and `t` is 1.0, or both are null (at any
/// `t` value).
///
/// If `T` is not nullable, then [begin] and [end] must both be set to
/// non-null values before using [lerp] or [transform], otherwise they
/// will throw.
224
class Tween<T extends Object?> extends Animatable<T> {
225 226
  /// Creates a tween.
  ///
227 228 229
  /// 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.
230 231 232 233
  Tween({
    this.begin,
    this.end,
  });
234 235

  /// The value this variable has at the beginning of the animation.
236
  ///
237 238
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
239
  T? begin;
240 241

  /// The value this variable has at the end of the animation.
242
  ///
243 244
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
245
  T? end;
246 247

  /// Returns the value this variable has at the given animation clock value.
248
  ///
249
  /// The default implementation of this method uses the `+`, `-`, and `*`
250 251
  /// operators on `T`. The [begin] and [end] properties must therefore be
  /// non-null by the time this method is called.
252 253 254
  ///
  /// In general, however, it is possible for this to return null, especially
  /// when `t`=0.0 and [begin] is null, or `t`=1.0 and [end] is null.
255
  @protected
256 257 258
  T lerp(double t) {
    assert(begin != null);
    assert(end != null);
259 260 261
    assert(() {
      // Assertions that attempt to catch common cases of tweening types
      // that do not conform to the Tween requirements.
262
      dynamic result;
263
      try {
264 265
        // ignore: avoid_dynamic_calls
        result = (begin as dynamic) + ((end as dynamic) - (begin as dynamic)) * t;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        result as T;
        return true;
      } on NoSuchMethodError {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('Cannot lerp between "$begin" and "$end".'),
          ErrorDescription(
            'The type ${begin.runtimeType} might not fully implement `+`, `-`, and/or `*`. '
            'See "Types with special considerations" at https://api.flutter.dev/flutter/animation/Tween-class.html '
            'for more information.',
          ),
          if (begin is Color || end is Color)
            ErrorHint('To lerp colors, consider ColorTween instead.')
          else if (begin is Rect || end is Rect)
            ErrorHint('To lerp rects, consider RectTween instead.')
          else
            ErrorHint(
              'There may be a dedicated "${begin.runtimeType}Tween" for this type, '
283
              'or you may need to create one.',
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
            ),
        ]);
      } on TypeError {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('Cannot lerp between "$begin" and "$end".'),
          ErrorDescription(
            'The type ${begin.runtimeType} returned a ${result.runtimeType} after '
            'multiplication with a double value. '
            'See "Types with special considerations" at https://api.flutter.dev/flutter/animation/Tween-class.html '
            'for more information.',
          ),
          if (begin is int || end is int)
            ErrorHint('To lerp int values, consider IntTween or StepTween instead.')
          else
            ErrorHint(
              'There may be a dedicated "${begin.runtimeType}Tween" for this type, '
300
              'or you may need to create one.',
301 302 303 304
            ),
        ]);
      }
    }());
305 306
    // ignore: avoid_dynamic_calls
    return (begin as dynamic) + ((end as dynamic) - (begin as dynamic)) * t as T;
307
  }
308

309
  /// Returns the interpolated value for the current value of the given animation.
310
  ///
311 312 313
  /// This method returns `begin` and `end` when the animation values are 0.0 or
  /// 1.0, respectively.
  ///
314 315 316
  /// This function is implemented by deferring to [lerp]. Subclasses that want
  /// to provide custom behavior should override [lerp], not [transform] (nor
  /// [evaluate]).
317 318 319 320
  ///
  /// 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.
321
  @override
322
  T transform(double t) {
323
    if (t == 0.0)
324
      return begin as T;
325
    if (t == 1.0)
326
      return end as T;
327 328
    return lerp(t);
  }
329

330
  @override
331
  String toString() => '${objectRuntimeType(this, 'Animatable')}($begin \u2192 $end)';
332 333
}

334
/// A [Tween] that evaluates its [parent] in reverse.
335
class ReverseTween<T extends Object?> extends Tween<T> {
336
  /// Construct a [Tween] that evaluates its [parent] in reverse.
337 338 339
  ReverseTween(this.parent)
    : assert(parent != null),
      super(begin: parent.end, end: parent.begin);
340 341 342 343 344 345 346 347 348 349 350 351

  /// 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);
}

352
/// An interpolation between two colors.
353
///
354 355 356
/// This class specializes the interpolation of [Tween<Color>] to use
/// [Color.lerp].
///
357 358 359
/// The values can be null, representing no color (which is distinct to
/// transparent black, as represented by [Colors.transparent]).
///
360
/// See [Tween] for a discussion on how to use interpolation objects.
361
class ColorTween extends Tween<Color?> {
362
  /// Creates a [Color] tween.
363
  ///
364
  /// The [begin] and [end] properties may be null; the null value
365 366 367 368 369 370
  /// 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.
371
  ColorTween({ Color? begin, Color? end }) : super(begin: begin, end: end);
372

373
  /// Returns the value this variable has at the given animation clock value.
374
  @override
375
  Color? lerp(double t) => Color.lerp(begin, end, t);
376 377
}

378
/// An interpolation between two sizes.
379
///
380 381 382
/// This class specializes the interpolation of [Tween<Size>] to use
/// [Size.lerp].
///
383 384
/// The values can be null, representing [Size.zero].
///
385
/// See [Tween] for a discussion on how to use interpolation objects.
386
class SizeTween extends Tween<Size?> {
387
  /// Creates a [Size] tween.
388
  ///
389 390
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty size.
391
  SizeTween({ Size? begin, Size? end }) : super(begin: begin, end: end);
392

393
  /// Returns the value this variable has at the given animation clock value.
394
  @override
395
  Size? lerp(double t) => Size.lerp(begin, end, t);
396 397
}

398
/// An interpolation between two rectangles.
399
///
400 401 402
/// This class specializes the interpolation of [Tween<Rect>] to use
/// [Rect.lerp].
///
403 404 405
/// The values can be null, representing a zero-sized rectangle at the
/// origin ([Rect.zero]).
///
406
/// See [Tween] for a discussion on how to use interpolation objects.
407
class RectTween extends Tween<Rect?> {
408
  /// Creates a [Rect] tween.
409
  ///
410 411
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty rect at the top left corner.
412
  RectTween({ Rect? begin, Rect? end }) : super(begin: begin, end: end);
413

414
  /// Returns the value this variable has at the given animation clock value.
415
  @override
416
  Rect? lerp(double t) => Rect.lerp(begin, end, t);
417 418
}

419
/// An interpolation between two integers that rounds.
420
///
421
/// This class specializes the interpolation of [Tween<int>] to be
422 423 424 425
/// appropriate for integers by interpolating between the given begin
/// and end values and then rounding the result to the nearest
/// integer.
///
426 427 428
/// This is the closest approximation to a linear tween that is possible with an
/// integer. Compare to [StepTween] and [Tween<double>].
///
429 430 431
/// The [begin] and [end] values must be set to non-null values before
/// calling [lerp] or [transform].
///
432
/// See [Tween] for a discussion on how to use interpolation objects.
433
class IntTween extends Tween<int> {
434 435
  /// Creates an int tween.
  ///
436 437 438
  /// 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.
439
  IntTween({ int? begin, int? end }) : super(begin: begin, end: end);
440 441 442

  // 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.
443
  @override
444
  int lerp(double t) => (begin! + (end! - begin!) * t).round();
445
}
446

447 448
/// An interpolation between two integers that floors.
///
449
/// This class specializes the interpolation of [Tween<int>] to be
450
/// appropriate for integers by interpolating between the given begin
451
/// and end values and then using [double.floor] to return the current
452 453 454 455
/// 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].
456
///
457 458 459
/// The [begin] and [end] values must be set to non-null values before
/// calling [lerp] or [transform].
///
460
/// See [Tween] for a discussion on how to use interpolation objects.
461
class StepTween extends Tween<int> {
462
  /// Creates an [int] tween that floors.
463
  ///
464 465 466
  /// 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.
467
  StepTween({ int? begin, int? end }) : super(begin: begin, end: end);
468 469 470

  // 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.
471
  @override
472
  int lerp(double t) => (begin! + (end! - begin!) * t).floor();
473 474
}

475 476 477 478 479
/// 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
480
  /// This tween doesn't interpolate, it always returns the same value.
481
  @override
482
  T lerp(double t) => begin as T;
483 484

  @override
485
  String toString() => '${objectRuntimeType(this, 'ConstantTween')}(value: $begin)';
486 487
}

488 489 490 491 492
/// 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].
493 494 495 496
/// ([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.)
///
497
/// {@tool snippet}
498 499 500 501 502
///
/// The following code snippet shows how you can apply a curve to a linear
/// animation produced by an [AnimationController] `controller`:
///
/// ```dart
503
/// final Animation<double> animation = _controller.drive(
504 505 506
///   CurveTween(curve: Curves.ease),
/// );
/// ```
507
/// {@end-tool}
508 509 510 511 512 513
///
/// See also:
///
///  * [CurvedAnimation], for an alternative way of expressing the sample above.
///  * [AnimationController], for examples of creating and disposing of an
///    [AnimationController].
514
class CurveTween extends Animatable<double> {
515 516 517
  /// Creates a curve tween.
  ///
  /// The [curve] argument must not be null.
518
  CurveTween({ required this.curve })
519
    : assert(curve != null);
520

521
  /// The curve to use when transforming the value of the animation.
522 523
  Curve curve;

524
  @override
525
  double transform(double t) {
526 527 528 529 530 531
    if (t == 0.0 || t == 1.0) {
      assert(curve.transform(t).round() == t);
      return t;
    }
    return curve.transform(t);
  }
532 533

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