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

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

9
import 'animations.dart';
10 11 12 13 14

export 'dart:ui' show Color, Rect, Size;

export 'animation.dart' show Animation;
export 'curves.dart' show Curve;
15

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

20 21
/// A typedef used by [Animatable.fromCallback] to create an [Animatable]
/// from a callback.
22
typedef AnimatableCallback<T> = T Function(double value);
23

24 25 26 27 28
/// 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.
29 30
///
/// The main subclass of [Animatable] is [Tween].
31
abstract class Animatable<T> {
32 33
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
34
  const Animatable();
35

36 37 38 39 40 41 42 43
  /// Create a new [Animatable] from the provided [callback].
  ///
  /// See also:
  ///
  ///  * [Animation.drive], which provides an example for how this can be
  ///    used.
  const factory Animatable.fromCallback(AnimatableCallback<T> callback) = _CallbackAnimatable<T>;

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /// 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);
69

70
  /// Returns a new [Animation] that is driven by the given animation but that
71
  /// takes on values determined by this object.
72 73 74 75 76 77 78 79
  ///
  /// 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.
80
  Animation<T> animate(Animation<double> parent) {
81
    return _AnimatedEvaluation<T>(parent, this);
82
  }
83

84
  /// Returns a new [Animatable] whose value is determined by first evaluating
85
  /// the given parent and then evaluating this object.
86 87
  ///
  /// This allows [Tween]s to be chained before obtaining an [Animation].
88
  Animatable<T> chain(Animatable<double> parent) {
89
    return _ChainedEvaluation<T>(parent, this);
90
  }
91 92
}

93 94 95 96 97 98 99 100 101 102 103 104
// A concrete subclass of `Animatable` used by `Animatable.fromCallback`.
class _CallbackAnimatable<T> extends Animatable<T> {
  const _CallbackAnimatable(this._callback);

  final AnimatableCallback<T> _callback;

  @override
  T transform(double t) {
    return _callback(t);
  }
}

105
class _AnimatedEvaluation<T> extends Animation<T> with AnimationWithParentMixin<double> {
106
  _AnimatedEvaluation(this.parent, this._evaluatable);
107

108
  @override
109
  final Animation<double> parent;
110

111
  final Animatable<T> _evaluatable;
112

113
  @override
114
  T get value => _evaluatable.evaluate(parent);
115 116 117

  @override
  String toString() {
118
    return '$parent\u27A9$_evaluatable\u27A9$value';
119 120 121 122 123 124
  }

  @override
  String toStringDetails() {
    return '${super.toStringDetails()} $_evaluatable';
  }
125 126
}

127
class _ChainedEvaluation<T> extends Animatable<T> {
128 129
  _ChainedEvaluation(this._parent, this._evaluatable);

130 131
  final Animatable<double> _parent;
  final Animatable<T> _evaluatable;
132

133
  @override
134 135
  T transform(double t) {
    return _evaluatable.transform(_parent.transform(t));
136
  }
137 138 139 140 141

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

144
/// A linear interpolation between a beginning and ending value.
145 146 147
///
/// [Tween] is useful if you want to interpolate across a range.
///
148
/// To use a [Tween] object with an animation, call the [Tween] object's
149
/// [animate] method and pass it the [Animation] object that you want to
150
/// modify.
151
///
152
/// You can chain [Tween] objects together using the [chain] method, so that a
153
/// single [Animation] object is configured by multiple [Tween] objects called
154
/// in succession. This is different than calling the [animate] method twice,
155
/// which results in two separate [Animation] objects, each configured with a
156
/// single [Tween].
157
///
158
/// {@tool snippet}
159 160 161
///
/// Suppose `_controller` is an [AnimationController], and we want to create an
/// [Animation<Offset>] that is controlled by that controller, and save it in
162 163 164 165 166 167 168 169 170 171
/// `_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),
///   ),
/// );
/// ```
172
/// {@end-tool}
173
/// {@tool snippet}
174 175
///
/// ```dart
176
/// _animation = Tween<Offset>(
177 178
///   begin: const Offset(100.0, 50.0),
///   end: const Offset(200.0, 300.0),
179
/// ).animate(_controller);
180
/// ```
181
/// {@end-tool}
182
///
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
/// 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].
///
200
/// If a [Tween]'s values are never changed, however, a further optimization can
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
/// 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).
237 238 239 240 241 242 243 244 245 246 247 248 249 250
///
/// ## 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.
251 252 253 254 255 256
///
/// ## Implementing a Tween
///
/// To specialize this class for a new type, the subclass should implement
/// the [lerp] method (and a constructor). The other methods of this class
/// are all defined in terms of [lerp].
257
class Tween<T extends Object?> extends Animatable<T> {
258 259
  /// Creates a tween.
  ///
260 261 262
  /// 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.
263 264 265 266
  Tween({
    this.begin,
    this.end,
  });
267 268

  /// The value this variable has at the beginning of the animation.
269
  ///
270 271
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
272
  T? begin;
273 274

  /// The value this variable has at the end of the animation.
275
  ///
276 277
  /// See the constructor for details about whether this property may be null
  /// (it varies from subclass to subclass).
278
  T? end;
279 280

  /// Returns the value this variable has at the given animation clock value.
281
  ///
282
  /// The default implementation of this method uses the `+`, `-`, and `*`
283 284
  /// operators on `T`. The [begin] and [end] properties must therefore be
  /// non-null by the time this method is called.
285 286 287
  ///
  /// 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.
288
  @protected
289 290 291
  T lerp(double t) {
    assert(begin != null);
    assert(end != null);
292 293 294
    assert(() {
      // Assertions that attempt to catch common cases of tweening types
      // that do not conform to the Tween requirements.
295
      dynamic result;
296
      try {
297 298
        // ignore: avoid_dynamic_calls
        result = (begin as dynamic) + ((end as dynamic) - (begin as dynamic)) * t;
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        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, '
316
              'or you may need to create one.',
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            ),
        ]);
      } 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, '
333
              'or you may need to create one.',
334 335 336 337
            ),
        ]);
      }
    }());
338 339
    // ignore: avoid_dynamic_calls
    return (begin as dynamic) + ((end as dynamic) - (begin as dynamic)) * t as T;
340
  }
341

342
  /// Returns the interpolated value for the current value of the given animation.
343
  ///
344 345 346
  /// This method returns `begin` and `end` when the animation values are 0.0 or
  /// 1.0, respectively.
  ///
347 348 349
  /// This function is implemented by deferring to [lerp]. Subclasses that want
  /// to provide custom behavior should override [lerp], not [transform] (nor
  /// [evaluate]).
350 351 352 353
  ///
  /// 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.
354
  @override
355
  T transform(double t) {
356
    if (t == 0.0) {
357
      return begin as T;
358 359
    }
    if (t == 1.0) {
360
      return end as T;
361
    }
362 363
    return lerp(t);
  }
364

365
  @override
366
  String toString() => '${objectRuntimeType(this, 'Animatable')}($begin \u2192 $end)';
367 368
}

369
/// A [Tween] that evaluates its [parent] in reverse.
370
class ReverseTween<T extends Object?> extends Tween<T> {
371
  /// Construct a [Tween] that evaluates its [parent] in reverse.
372
  ReverseTween(this.parent)
373
    : super(begin: parent.end, end: parent.begin);
374 375 376 377 378 379 380 381 382 383 384 385

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

386
/// An interpolation between two colors.
387
///
388 389 390
/// This class specializes the interpolation of [Tween<Color>] to use
/// [Color.lerp].
///
391 392 393
/// The values can be null, representing no color (which is distinct to
/// transparent black, as represented by [Colors.transparent]).
///
394
/// See [Tween] for a discussion on how to use interpolation objects.
395
class ColorTween extends Tween<Color?> {
396
  /// Creates a [Color] tween.
397
  ///
398
  /// The [begin] and [end] properties may be null; the null value
399 400 401 402 403 404
  /// 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.
405
  ColorTween({ super.begin, super.end });
406

407
  /// Returns the value this variable has at the given animation clock value.
408
  @override
409
  Color? lerp(double t) => Color.lerp(begin, end, t);
410 411
}

412
/// An interpolation between two sizes.
413
///
414 415 416
/// This class specializes the interpolation of [Tween<Size>] to use
/// [Size.lerp].
///
417 418
/// The values can be null, representing [Size.zero].
///
419
/// See [Tween] for a discussion on how to use interpolation objects.
420
class SizeTween extends Tween<Size?> {
421
  /// Creates a [Size] tween.
422
  ///
423 424
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty size.
425
  SizeTween({ super.begin, super.end });
426

427
  /// Returns the value this variable has at the given animation clock value.
428
  @override
429
  Size? lerp(double t) => Size.lerp(begin, end, t);
430 431
}

432
/// An interpolation between two rectangles.
433
///
434 435 436
/// This class specializes the interpolation of [Tween<Rect>] to use
/// [Rect.lerp].
///
437 438 439
/// The values can be null, representing a zero-sized rectangle at the
/// origin ([Rect.zero]).
///
440
/// See [Tween] for a discussion on how to use interpolation objects.
441
class RectTween extends Tween<Rect?> {
442
  /// Creates a [Rect] tween.
443
  ///
444 445
  /// The [begin] and [end] properties may be null; the null value
  /// is treated as an empty rect at the top left corner.
446
  RectTween({ super.begin, super.end });
447

448
  /// Returns the value this variable has at the given animation clock value.
449
  @override
450
  Rect? lerp(double t) => Rect.lerp(begin, end, t);
451 452
}

453
/// An interpolation between two integers that rounds.
454
///
455
/// This class specializes the interpolation of [Tween<int>] to be
456 457 458 459
/// appropriate for integers by interpolating between the given begin
/// and end values and then rounding the result to the nearest
/// integer.
///
460 461 462
/// This is the closest approximation to a linear tween that is possible with an
/// integer. Compare to [StepTween] and [Tween<double>].
///
463 464 465
/// The [begin] and [end] values must be set to non-null values before
/// calling [lerp] or [transform].
///
466
/// See [Tween] for a discussion on how to use interpolation objects.
467
class IntTween extends Tween<int> {
468 469
  /// Creates an int tween.
  ///
470 471 472
  /// 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.
473
  IntTween({ super.begin, super.end });
474 475 476

  // 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.
477
  @override
478
  int lerp(double t) => (begin! + (end! - begin!) * t).round();
479
}
480

481 482
/// An interpolation between two integers that floors.
///
483
/// This class specializes the interpolation of [Tween<int>] to be
484
/// appropriate for integers by interpolating between the given begin
485
/// and end values and then using [double.floor] to return the current
486 487 488 489
/// 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].
490
///
491 492 493
/// The [begin] and [end] values must be set to non-null values before
/// calling [lerp] or [transform].
///
494
/// See [Tween] for a discussion on how to use interpolation objects.
495
class StepTween extends Tween<int> {
496
  /// Creates an [int] tween that floors.
497
  ///
498 499 500
  /// 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.
501
  StepTween({ super.begin, super.end });
502 503 504

  // 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.
505
  @override
506
  int lerp(double t) => (begin! + (end! - begin!) * t).floor();
507 508
}

509 510 511 512 513
/// 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
514
  /// This tween doesn't interpolate, it always returns the same value.
515
  @override
516
  T lerp(double t) => begin as T;
517 518

  @override
519
  String toString() => '${objectRuntimeType(this, 'ConstantTween')}(value: $begin)';
520 521
}

522 523 524 525 526
/// 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].
527 528 529 530
/// ([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.)
///
531
/// {@tool snippet}
532 533 534 535 536
///
/// The following code snippet shows how you can apply a curve to a linear
/// animation produced by an [AnimationController] `controller`:
///
/// ```dart
537
/// final Animation<double> animation = _controller.drive(
538 539 540
///   CurveTween(curve: Curves.ease),
/// );
/// ```
541
/// {@end-tool}
542 543 544 545 546 547
///
/// See also:
///
///  * [CurvedAnimation], for an alternative way of expressing the sample above.
///  * [AnimationController], for examples of creating and disposing of an
///    [AnimationController].
548
class CurveTween extends Animatable<double> {
549
  /// Creates a curve tween.
550
  CurveTween({ required this.curve });
551

552
  /// The curve to use when transforming the value of the animation.
553 554
  Curve curve;

555
  @override
556
  double transform(double t) {
557 558 559 560 561 562
    if (t == 0.0 || t == 1.0) {
      assert(curve.transform(t).round() == t);
      return t;
    }
    return curve.transform(t);
  }
563 564

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