drive<U> method

  1. @optionalTypeArgs
Animation<U> drive <U>(
  1. Animatable<U> child
)
@optionalTypeArgs

Chains a Tween (or CurveTween) to this Animation.

This method is only valid for Animation<double> instances (i.e. when T is double). This means, for instance, that it can be called on AnimationController objects, as well as CurvedAnimations, ProxyAnimations, ReverseAnimations, TrainHoppingAnimations, etc.

It returns an Animation specialized to the same type, U, as the argument to the method (child), whose value is derived by applying the given Tween to the value of this Animation.

Given an AnimationController _controller, the following code creates an Animation<Alignment> that swings from top left to top right as the controller goes from 0.0 to 1.0:
Animation<Alignment> _alignment1 = _controller.drive(
  AlignmentTween(
    begin: Alignment.topLeft,
    end: Alignment.topRight,
  ),
);

The _alignment.value could then be used in a widget's build method, for instance, to position a child using an Align widget such that the position of the child shifts over time from the top left to the top right.

It is common to ease this kind of curve, e.g. making the transition slower at the start and faster at the end. The following snippet shows one way to chain the alignment tween in the previous example to an easing curve (in this case, Curves.easeIn). In this example, the tween is created elsewhere as a variable that can be reused, since none of its arguments vary.

final Animatable<Alignment> _tween = AlignmentTween(begin: Alignment.topLeft, end: Alignment.topRight)
  .chain(CurveTween(curve: Curves.easeIn));
// ...
Animation<Alignment> _alignment2 = _controller.drive(_tween);

The following code is exactly equivalent, and is typically clearer when the tweens are created inline, as might be preferred when the tweens have values that depend on other variables:
Animation<Alignment> _alignment3 = _controller
  .drive(CurveTween(curve: Curves.easeIn))
  .drive(AlignmentTween(
    begin: Alignment.topLeft,
    end: Alignment.topRight,
  ));

See also:

Implementation

@optionalTypeArgs
Animation<U> drive<U>(Animatable<U> child) {
  assert(this is Animation<double>);
  return child.animate(this as dynamic); // TODO(ianh): Clean this once https://github.com/dart-lang/sdk/issues/32120 is fixed.
}