| 1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | /// @docImport 'package:flutter/scheduler.dart'; |
| 6 | /// @docImport 'package:flutter/widgets.dart'; |
| 7 | library; |
| 8 | |
| 9 | import 'package:flutter/foundation.dart'; |
| 10 | |
| 11 | import 'tween.dart'; |
| 12 | |
| 13 | export 'dart:ui' show VoidCallback; |
| 14 | |
| 15 | export 'tween.dart' show Animatable; |
| 16 | |
| 17 | // Examples can assume: |
| 18 | // late AnimationController _controller; |
| 19 | // late ValueNotifier _scrollPosition; |
| 20 | |
| 21 | /// The status of an animation. |
| 22 | enum AnimationStatus { |
| 23 | /// The animation is stopped at the beginning. |
| 24 | dismissed, |
| 25 | |
| 26 | /// The animation is running from beginning to end. |
| 27 | forward, |
| 28 | |
| 29 | /// The animation is running backwards, from end to beginning. |
| 30 | reverse, |
| 31 | |
| 32 | /// The animation is stopped at the end. |
| 33 | completed; |
| 34 | |
| 35 | /// Whether the animation is stopped at the beginning. |
| 36 | bool get isDismissed => this == dismissed; |
| 37 | |
| 38 | /// Whether the animation is stopped at the end. |
| 39 | bool get isCompleted => this == completed; |
| 40 | |
| 41 | /// Whether the animation is running in either direction. |
| 42 | bool get isAnimating => switch (this) { |
| 43 | forward || reverse => true, |
| 44 | completed || dismissed => false, |
| 45 | }; |
| 46 | |
| 47 | /// {@template flutter.animation.AnimationStatus.isForwardOrCompleted} |
| 48 | /// Whether the current aim of the animation is toward completion. |
| 49 | /// |
| 50 | /// Specifically, returns `true` for [AnimationStatus.forward] or |
| 51 | /// [AnimationStatus.completed], and `false` for |
| 52 | /// [AnimationStatus.reverse] or [AnimationStatus.dismissed]. |
| 53 | /// {@endtemplate} |
| 54 | bool get isForwardOrCompleted => switch (this) { |
| 55 | forward || completed => true, |
| 56 | reverse || dismissed => false, |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | /// Signature for listeners attached using [Animation.addStatusListener]. |
| 61 | typedef AnimationStatusListener = void Function(AnimationStatus status); |
| 62 | |
| 63 | /// Signature for method used to transform values in [Animation.fromValueListenable]. |
| 64 | typedef ValueListenableTransformer<T> = T Function(T); |
| 65 | |
| 66 | /// A value which might change over time, moving forward or backward. |
| 67 | /// |
| 68 | /// An animation has a [value] (of type [T]) and a [status]. |
| 69 | /// The value conceptually lies on some path, and |
| 70 | /// the status indicates how the value is currently moving along the path: |
| 71 | /// forward, backward, or stopped at the end or the beginning. |
| 72 | /// The path may double back on itself |
| 73 | /// (e.g., if the animation uses a curve that bounces), |
| 74 | /// so even when the animation is conceptually moving forward |
| 75 | /// the value might not change monotonically. |
| 76 | /// |
| 77 | /// Consumers of the animation can listen for changes to either the value |
| 78 | /// or the status, with [addListener] and [addStatusListener]. |
| 79 | /// The listener callbacks are called during the "animation" phase of |
| 80 | /// the pipeline, just prior to rebuilding widgets. |
| 81 | /// |
| 82 | /// An animation might move forward or backward on its own as time passes |
| 83 | /// (like the opacity of a button that fades over a fixed duration |
| 84 | /// once the user touches it), |
| 85 | /// or it might be driven by the user |
| 86 | /// (like the position of a slider that the user can drag back and forth), |
| 87 | /// or it might do both |
| 88 | /// (like a switch that snaps into place when released, |
| 89 | /// or a [Dismissible] that responds to drag and fling gestures, etc.). |
| 90 | /// The behavior is normally controlled by method calls on |
| 91 | /// some underlying [AnimationController]. |
| 92 | /// When an animation is actively animating, it typically updates on |
| 93 | /// each frame, driven by a [Ticker]. |
| 94 | /// |
| 95 | /// ## Using animations |
| 96 | /// |
| 97 | /// For simple animation effects, consider using one of the |
| 98 | /// [ImplicitlyAnimatedWidget] subclasses, |
| 99 | /// like [AnimatedScale], [AnimatedOpacity], and many others. |
| 100 | /// When an [ImplicitlyAnimatedWidget] suffices, there is |
| 101 | /// no need to work with [Animation] or the rest of the classes |
| 102 | /// discussed in this section. |
| 103 | /// |
| 104 | /// Otherwise, typically an animation originates with an [AnimationController] |
| 105 | /// (which is itself an [Animation<double>]) |
| 106 | /// created by a [State] that implements [TickerProvider]. |
| 107 | /// Further animations might be derived from that animation |
| 108 | /// by using e.g. [Tween] or [CurvedAnimation]. |
| 109 | /// The animations might be used to configure an [AnimatedWidget] |
| 110 | /// (using one of its many subclasses like [FadeTransition]), |
| 111 | /// or their values might be used directly. |
| 112 | /// |
| 113 | /// For example, the [AnimationController] may represent |
| 114 | /// the abstract progress of the animation from 0.0 to 1.0; |
| 115 | /// then a [CurvedAnimation] might apply an easing curve; |
| 116 | /// and a [SizeTween] and [ColorTween] might each be applied to that |
| 117 | /// to produce an [Animation<Size>] and an [Animation<Color>] that control |
| 118 | /// a widget shrinking and changing color as the animation proceeds. |
| 119 | /// |
| 120 | /// ## Performance considerations |
| 121 | /// |
| 122 | /// Because the [Animation] keeps the same identity as the animation proceeds, |
| 123 | /// it provides a convenient way for a [StatefulWidget] that orchestrates |
| 124 | /// a complex animation to communicate the animation's progress to its |
| 125 | /// various child widgets. Consider having higher-level widgets in the tree |
| 126 | /// pass lower-level widgets the [Animation] itself, rather than its value, |
| 127 | /// in order to avoid rebuilding the higher-level widgets on each frame |
| 128 | /// even while the animation is active. |
| 129 | /// If the leaf widgets also ignore [value] and pass the whole |
| 130 | /// [Animation] object to a render object (like [FadeTransition] does), |
| 131 | /// they too might be able to avoid rebuild and even relayout, so that the |
| 132 | /// only work needed on each frame of the animation is to repaint. |
| 133 | /// |
| 134 | /// See also: |
| 135 | /// |
| 136 | /// * [ImplicitlyAnimatedWidget] and its subclasses, which provide |
| 137 | /// animation effects without the need to manually work with [Animation], |
| 138 | /// [AnimationController], or even [State]. |
| 139 | /// * [AnimationController], an animation you can run forward and backward, |
| 140 | /// stop, or set to a specific value. |
| 141 | /// * [Tween], which can be used to convert [Animation<double>]s into |
| 142 | /// other kinds of [Animation]s. |
| 143 | /// * [AnimatedWidget] and its subclasses, which provide animation effects |
| 144 | /// that can be controlled by an [Animation]. |
| 145 | abstract class Animation<T> extends Listenable implements ValueListenable<T> { |
| 146 | /// Abstract const constructor. This constructor enables subclasses to provide |
| 147 | /// const constructors so that they can be used in const expressions. |
| 148 | const Animation(); |
| 149 | |
| 150 | /// Create a new animation from a [ValueListenable]. |
| 151 | /// |
| 152 | /// The returned animation will always have an animation status of |
| 153 | /// [AnimationStatus.forward]. The value of the provided listenable can |
| 154 | /// be optionally transformed using the [transformer] function. |
| 155 | /// |
| 156 | /// {@tool snippet} |
| 157 | /// |
| 158 | /// This constructor can be used to replace instances of [ValueListenableBuilder] |
| 159 | /// widgets with a corresponding animated widget, like a [FadeTransition]. |
| 160 | /// |
| 161 | /// Before: |
| 162 | /// |
| 163 | /// ```dart |
| 164 | /// Widget build(BuildContext context) { |
| 165 | /// return ValueListenableBuilder<double>( |
| 166 | /// valueListenable: _scrollPosition, |
| 167 | /// builder: (BuildContext context, double value, Widget? child) { |
| 168 | /// final double opacity = (value / 1000).clamp(0, 1); |
| 169 | /// return Opacity(opacity: opacity, child: child); |
| 170 | /// }, |
| 171 | /// child: const ColoredBox( |
| 172 | /// color: Colors.red, |
| 173 | /// child: Text('Hello, Animation'), |
| 174 | /// ), |
| 175 | /// ); |
| 176 | /// } |
| 177 | /// ``` |
| 178 | /// |
| 179 | /// {@end-tool} |
| 180 | /// {@tool snippet} |
| 181 | /// |
| 182 | /// After: |
| 183 | /// |
| 184 | /// ```dart |
| 185 | /// Widget build2(BuildContext context) { |
| 186 | /// return FadeTransition( |
| 187 | /// opacity: Animation<double>.fromValueListenable(_scrollPosition, transformer: (double value) { |
| 188 | /// return (value / 1000).clamp(0, 1); |
| 189 | /// }), |
| 190 | /// child: const ColoredBox( |
| 191 | /// color: Colors.red, |
| 192 | /// child: Text('Hello, Animation'), |
| 193 | /// ), |
| 194 | /// ); |
| 195 | /// } |
| 196 | /// ``` |
| 197 | /// {@end-tool} |
| 198 | factory Animation.fromValueListenable( |
| 199 | ValueListenable<T> listenable, { |
| 200 | ValueListenableTransformer<T>? transformer, |
| 201 | }) = _ValueListenableDelegateAnimation<T>; |
| 202 | |
| 203 | // keep these next five dartdocs in sync with the dartdocs in AnimationWithParentMixin |
| 204 | |
| 205 | /// Calls the listener every time the value of the animation changes. |
| 206 | /// |
| 207 | /// Listeners can be removed with [removeListener]. |
| 208 | @override |
| 209 | void addListener(VoidCallback listener); |
| 210 | |
| 211 | /// Stop calling the listener every time the value of the animation changes. |
| 212 | /// |
| 213 | /// If `listener` is not currently registered as a listener, this method does |
| 214 | /// nothing. |
| 215 | /// |
| 216 | /// Listeners can be added with [addListener]. |
| 217 | @override |
| 218 | void removeListener(VoidCallback listener); |
| 219 | |
| 220 | /// Calls listener every time the status of the animation changes. |
| 221 | /// |
| 222 | /// Listeners can be removed with [removeStatusListener]. |
| 223 | void addStatusListener(AnimationStatusListener listener); |
| 224 | |
| 225 | /// Stops calling the listener every time the status of the animation changes. |
| 226 | /// |
| 227 | /// If `listener` is not currently registered as a status listener, this |
| 228 | /// method does nothing. |
| 229 | /// |
| 230 | /// Listeners can be added with [addStatusListener]. |
| 231 | void removeStatusListener(AnimationStatusListener listener); |
| 232 | |
| 233 | /// The current status of this animation. |
| 234 | AnimationStatus get status; |
| 235 | |
| 236 | /// The current value of the animation. |
| 237 | @override |
| 238 | T get value; |
| 239 | |
| 240 | /// Whether this animation is stopped at the beginning. |
| 241 | bool get isDismissed => status.isDismissed; |
| 242 | |
| 243 | /// Whether this animation is stopped at the end. |
| 244 | bool get isCompleted => status.isCompleted; |
| 245 | |
| 246 | /// Whether this animation is running in either direction. |
| 247 | /// |
| 248 | /// By default, this value is equal to `status.isAnimating`, but |
| 249 | /// [AnimationController] overrides this method so that its output |
| 250 | /// depends on whether the controller is actively ticking. |
| 251 | bool get isAnimating => status.isAnimating; |
| 252 | |
| 253 | /// {@macro flutter.animation.AnimationStatus.isForwardOrCompleted} |
| 254 | bool get isForwardOrCompleted => status.isForwardOrCompleted; |
| 255 | |
| 256 | /// Chains a [Tween] (or [CurveTween]) to this [Animation]. |
| 257 | /// |
| 258 | /// This method is only valid for `Animation<double>` instances (i.e. when `T` |
| 259 | /// is `double`). This means, for instance, that it can be called on |
| 260 | /// [AnimationController] objects, as well as [CurvedAnimation]s, |
| 261 | /// [ProxyAnimation]s, [ReverseAnimation]s, [TrainHoppingAnimation]s, etc. |
| 262 | /// |
| 263 | /// It returns an [Animation] specialized to the same type, `U`, as the |
| 264 | /// argument to the method (`child`), whose value is derived by applying the |
| 265 | /// given [Tween] to the value of this [Animation]. |
| 266 | /// |
| 267 | /// {@tool snippet} |
| 268 | /// |
| 269 | /// Given an [AnimationController] `_controller`, the following code creates |
| 270 | /// an `Animation<Alignment>` that swings from top left to top right as the |
| 271 | /// controller goes from 0.0 to 1.0: |
| 272 | /// |
| 273 | /// ```dart |
| 274 | /// Animation<Alignment> alignment1 = _controller.drive( |
| 275 | /// AlignmentTween( |
| 276 | /// begin: Alignment.topLeft, |
| 277 | /// end: Alignment.topRight, |
| 278 | /// ), |
| 279 | /// ); |
| 280 | /// ``` |
| 281 | /// {@end-tool} |
| 282 | /// {@tool snippet} |
| 283 | /// |
| 284 | /// The `alignment1.value` could then be used in a widget's build method, for |
| 285 | /// instance, to position a child using an [Align] widget such that the |
| 286 | /// position of the child shifts over time from the top left to the top right. |
| 287 | /// |
| 288 | /// It is common to ease this kind of curve, e.g. making the transition slower |
| 289 | /// at the start and faster at the end. The following snippet shows one way to |
| 290 | /// chain the alignment tween in the previous example to an easing curve (in |
| 291 | /// this case, [Curves.easeIn]). In this example, the tween is created |
| 292 | /// elsewhere as a variable that can be reused, since none of its arguments |
| 293 | /// vary. |
| 294 | /// |
| 295 | /// ```dart |
| 296 | /// final Animatable<Alignment> tween = AlignmentTween(begin: Alignment.topLeft, end: Alignment.topRight) |
| 297 | /// .chain(CurveTween(curve: Curves.easeIn)); |
| 298 | /// // ... |
| 299 | /// final Animation<Alignment> alignment2 = _controller.drive(tween); |
| 300 | /// ``` |
| 301 | /// {@end-tool} |
| 302 | /// {@tool snippet} |
| 303 | /// |
| 304 | /// The following code is exactly equivalent, and is typically clearer when |
| 305 | /// the tweens are created inline, as might be preferred when the tweens have |
| 306 | /// values that depend on other variables: |
| 307 | /// |
| 308 | /// ```dart |
| 309 | /// Animation<Alignment> alignment3 = _controller |
| 310 | /// .drive(CurveTween(curve: Curves.easeIn)) |
| 311 | /// .drive(AlignmentTween( |
| 312 | /// begin: Alignment.topLeft, |
| 313 | /// end: Alignment.topRight, |
| 314 | /// )); |
| 315 | /// ``` |
| 316 | /// {@end-tool} |
| 317 | /// {@tool snippet} |
| 318 | /// |
| 319 | /// This method can be paired with an [Animatable] created via |
| 320 | /// [Animatable.fromCallback] in order to transform an animation with a |
| 321 | /// callback function. This can be useful for performing animations that |
| 322 | /// do not have well defined start or end points. This example transforms |
| 323 | /// the current scroll position into a color that cycles through values |
| 324 | /// of red. |
| 325 | /// |
| 326 | /// ```dart |
| 327 | /// Animation<Color> color = Animation<double>.fromValueListenable(_scrollPosition) |
| 328 | /// .drive(Animatable<Color>.fromCallback((double value) { |
| 329 | /// return Color.fromRGBO(value.round() % 255, 0, 0, 1); |
| 330 | /// })); |
| 331 | /// ``` |
| 332 | /// |
| 333 | /// {@end-tool} |
| 334 | /// |
| 335 | /// See also: |
| 336 | /// |
| 337 | /// * [Animatable.animate], which does the same thing. |
| 338 | /// * [AnimationController], which is usually used to drive animations. |
| 339 | /// * [CurvedAnimation], an alternative to [CurveTween] for applying easing |
| 340 | /// curves, which supports distinct curves in the forward direction and the |
| 341 | /// reverse direction. |
| 342 | /// * [Animatable.fromCallback], which allows creating an [Animatable] from an |
| 343 | /// arbitrary transformation. |
| 344 | @optionalTypeArgs |
| 345 | Animation<U> drive<U>(Animatable<U> child) { |
| 346 | assert(this is Animation<double>); |
| 347 | return child.animate(this as Animation<double>); |
| 348 | } |
| 349 | |
| 350 | @override |
| 351 | String toString() { |
| 352 | return ' ${describeIdentity(this)}( ${toStringDetails()})' ; |
| 353 | } |
| 354 | |
| 355 | /// Provides a string describing the status of this object, but not including |
| 356 | /// information about the object itself. |
| 357 | /// |
| 358 | /// This function is used by [Animation.toString] so that [Animation] |
| 359 | /// subclasses can provide additional details while ensuring all [Animation] |
| 360 | /// subclasses have a consistent [toString] style. |
| 361 | /// |
| 362 | /// The result of this function includes an icon describing the status of this |
| 363 | /// [Animation] object: |
| 364 | /// |
| 365 | /// * "▶": [AnimationStatus.forward] ([value] increasing) |
| 366 | /// * "◀": [AnimationStatus.reverse] ([value] decreasing) |
| 367 | /// * "⏭": [AnimationStatus.completed] ([value] == 1.0) |
| 368 | /// * "⏮": [AnimationStatus.dismissed] ([value] == 0.0) |
| 369 | String toStringDetails() { |
| 370 | return switch (status) { |
| 371 | AnimationStatus.forward => '\u25B6' , // > |
| 372 | AnimationStatus.reverse => '\u25C0' , // < |
| 373 | AnimationStatus.completed => '\u23ED' , // >>| |
| 374 | AnimationStatus.dismissed => '\u23EE' , // |<< |
| 375 | }; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | // An implementation of an animation that delegates to a value listenable with a fixed direction. |
| 380 | class _ValueListenableDelegateAnimation<T> extends Animation<T> { |
| 381 | _ValueListenableDelegateAnimation(this._listenable, {ValueListenableTransformer<T>? transformer}) |
| 382 | : _transformer = transformer; |
| 383 | |
| 384 | final ValueListenable<T> _listenable; |
| 385 | final ValueListenableTransformer<T>? _transformer; |
| 386 | |
| 387 | @override |
| 388 | void addListener(VoidCallback listener) { |
| 389 | _listenable.addListener(listener); |
| 390 | } |
| 391 | |
| 392 | @override |
| 393 | void addStatusListener(AnimationStatusListener listener) { |
| 394 | // status will never change. |
| 395 | } |
| 396 | |
| 397 | @override |
| 398 | void removeListener(VoidCallback listener) { |
| 399 | _listenable.removeListener(listener); |
| 400 | } |
| 401 | |
| 402 | @override |
| 403 | void removeStatusListener(AnimationStatusListener listener) { |
| 404 | // status will never change. |
| 405 | } |
| 406 | |
| 407 | @override |
| 408 | AnimationStatus get status => AnimationStatus.forward; |
| 409 | |
| 410 | @override |
| 411 | T get value => _transformer?.call(_listenable.value) ?? _listenable.value; |
| 412 | } |
| 413 | |