animated_cross_fade.dart 13.1 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/foundation.dart';
6 7 8 9 10
import 'package:flutter/rendering.dart';

import 'animated_size.dart';
import 'basic.dart';
import 'framework.dart';
11
import 'ticker_provider.dart';
12 13
import 'transitions.dart';

14
/// Specifies which of two children to show. See [AnimatedCrossFade].
15 16 17
///
/// The child that is shown will fade in, while the other will fade out.
enum CrossFadeState {
18 19
  /// Show the first child ([AnimatedCrossFade.firstChild]) and hide the second
  /// ([AnimatedCrossFade.secondChild]]).
20
  showFirst,
21

22 23 24
  /// Show the second child ([AnimatedCrossFade.secondChild]) and hide the first
  /// ([AnimatedCrossFade.firstChild]).
  showSecond,
25 26
}

27 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 54 55 56 57 58 59 60 61 62
/// Signature for the [AnimatedCrossFade.layoutBuilder] callback.
///
/// The `topChild` is the child fading in, which is normally drawn on top. The
/// `bottomChild` is the child fading out, normally drawn on the bottom.
///
/// For good performance, the returned widget tree should contain both the
/// `topChild` and the `bottomChild`; the depth of the tree, and the types of
/// the widgets in the tree, from the returned widget to each of the children
/// should be the same; and where there is a widget with multiple children, the
/// top child and the bottom child should be keyed using the provided
/// `topChildKey` and `bottomChildKey` keys respectively.
///
/// ## Sample code
///
/// ```dart
/// Widget defaultLayoutBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey) {
///   return new Stack(
///     fit: StackFit.loose,
///     children: <Widget>[
///       new Positioned(
///         key: bottomChildKey,
///         left: 0.0,
///         top: 0.0,
///         right: 0.0,
///         child: bottomChild,
///       ),
///       new Positioned(
///         key: topChildKey,
///         child: topChild,
///       )
///     ],
///   );
/// }
/// ```
typedef Widget AnimatedCrossFadeBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey);

63 64 65 66 67
/// A widget that cross-fades between two given children and animates itself
/// between their sizes.
///
/// The animation is controlled through the [crossFadeState] parameter.
/// [firstCurve] and [secondCurve] represent the opacity curves of the two
68 69
/// children. The [firstCurve] is inverted, i.e. it fades out when providing a
/// growing curve like [Curves.linear]. The [sizeCurve] is the curve used to
70 71
/// animate between the size of the fading-out child and the size of the
/// fading-in child.
72 73 74 75 76
///
/// This widget is intended to be used to fade a pair of widgets with the same
/// width. In the case where the two children have different heights, the
/// animation crops overflowing children during the animation by aligning their
/// top edge, which means that the bottom will be clipped.
77
///
78 79 80 81
/// The animation is automatically triggered when an existing
/// [AnimatedCrossFade] is rebuilt with a different value for the
/// [crossFadeState] property.
///
82 83 84
/// ## Sample code
///
/// This code fades between two representations of the Flutter logo. It depends
85
/// on a boolean field `_first`; when `_first` is true, the first logo is shown,
86 87 88
/// otherwise the second logo is shown. When the field changes state, the
/// [AnimatedCrossFade] widget cross-fades between the two forms of the logo
/// over three seconds.
89 90 91 92 93 94
///
/// ```dart
/// new AnimatedCrossFade(
///   duration: const Duration(seconds: 3),
///   firstChild: const FlutterLogo(style: FlutterLogoStyle.horizontal, size: 100.0),
///   secondChild: const FlutterLogo(style: FlutterLogoStyle.stacked, size: 100.0),
95
///   crossFadeState: _first ? CrossFadeState.showFirst : CrossFadeState.showSecond,
96 97 98 99 100 101 102
/// )
/// ```
///
/// See also:
///
///  * [AnimatedSize], the lower-level widget which [AnimatedCrossFade] uses to
///    automatically change size.
103
class AnimatedCrossFade extends StatefulWidget {
104
  /// Creates a cross-fade animation widget.
105 106 107 108
  ///
  /// The [duration] of the animation is the same for all components (fade in,
  /// fade out, and size), and you can pass [Interval]s instead of [Curve]s in
  /// order to have finer control, e.g., creating an overlap between the fades.
109 110
  ///
  /// All the arguments other than [key] must be non-null.
111
  const AnimatedCrossFade({
112
    Key key,
113 114
    @required this.firstChild,
    @required this.secondChild,
115 116 117
    this.firstCurve: Curves.linear,
    this.secondCurve: Curves.linear,
    this.sizeCurve: Curves.linear,
118
    this.alignment: Alignment.topCenter,
119
    @required this.crossFadeState,
120 121 122 123 124
    @required this.duration,
    this.layoutBuilder: defaultLayoutBuilder,
  }) : assert(firstChild != null),
       assert(secondChild != null),
       assert(firstCurve != null),
125 126
       assert(secondCurve != null),
       assert(sizeCurve != null),
127 128 129 130
       assert(alignment != null),
       assert(crossFadeState != null),
       assert(duration != null),
       assert(layoutBuilder != null),
131
       super(key: key);
132

Ian Hickson's avatar
Ian Hickson committed
133 134 135
  /// The child that is visible when [crossFadeState] is
  /// [CrossFadeState.showFirst]. It fades out when transitioning
  /// [crossFadeState] from [CrossFadeState.showFirst] to
136
  /// [CrossFadeState.showSecond] and vice versa.
137 138
  final Widget firstChild;

Ian Hickson's avatar
Ian Hickson committed
139 140 141
  /// The child that is visible when [crossFadeState] is
  /// [CrossFadeState.showSecond]. It fades in when transitioning
  /// [crossFadeState] from [CrossFadeState.showFirst] to
142
  /// [CrossFadeState.showSecond] and vice versa.
143 144
  final Widget secondChild;

145
  /// The child that will be shown when the animation has completed.
146 147 148 149 150 151
  final CrossFadeState crossFadeState;

  /// The duration of the whole orchestrated animation.
  final Duration duration;

  /// The fade curve of the first child.
152 153
  ///
  /// Defaults to [Curves.linear].
154 155 156
  final Curve firstCurve;

  /// The fade curve of the second child.
157 158
  ///
  /// Defaults to [Curves.linear].
159 160 161
  final Curve secondCurve;

  /// The curve of the animation between the two children's sizes.
162 163
  ///
  /// Defaults to [Curves.linear].
164 165
  final Curve sizeCurve;

166 167
  /// How the children should be aligned while the size is animating.
  ///
168
  /// Defaults to [Alignment.topCenter].
169 170 171 172 173 174 175
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
176
  final AlignmentGeometry alignment;
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 212 213 214 215 216 217 218 219 220
  /// A builder that positions the [firstChild] and [secondChild] widgets.
  ///
  /// The widget returned by this method is wrapped in an [AnimatedSize].
  ///
  /// By default, this uses [AnimatedCrossFade.defaultLayoutBuilder], which uses
  /// a [Stack] and aligns the `bottomChild` to the top of the stack while
  /// providing the `topChild` as the non-positioned child to fill the provided
  /// constraints. This works well when the [AnimatedCrossFade] is in a position
  /// to change size and when the children are not flexible. However, if the
  /// children are less fussy about their sizes (for example a
  /// [CircularProgressIndicator] inside a [Center]), or if the
  /// [AnimatedCrossFade] is being forced to a particular size, then it can
  /// result in the widgets jumping about when the cross-fade state is changed.
  final AnimatedCrossFadeBuilder layoutBuilder;

  /// The default layout algorithm used by [AnimatedCrossFade].
  ///
  /// The top child is placed in a stack that sizes itself to match the top
  /// child. The bottom child is positioned at the top of the same stack, sized
  /// to fit its width but without forcing the height. The stack is then
  /// clipped.
  ///
  /// This is the default value for [layoutBuilder]. It implements
  /// [AnimatedCrossFadeBuilder].
  static Widget defaultLayoutBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey) {
    return new Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        new Positioned(
          key: bottomChildKey,
          left: 0.0,
          top: 0.0,
          right: 0.0,
          child: bottomChild,
        ),
        new Positioned(
          key: topChildKey,
          child: topChild,
        )
      ],
    );
  }

221 222
  @override
  _AnimatedCrossFadeState createState() => new _AnimatedCrossFadeState();
223 224

  @override
225 226 227 228
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<CrossFadeState>('crossFadeState', crossFadeState));
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: Alignment.topCenter));
229
  }
230 231
}

232
class _AnimatedCrossFadeState extends State<AnimatedCrossFade> with TickerProviderStateMixin {
233 234 235 236
  AnimationController _controller;
  Animation<double> _firstAnimation;
  Animation<double> _secondAnimation;

237 238 239
  @override
  void initState() {
    super.initState();
240 241
    _controller = new AnimationController(duration: widget.duration, vsync: this);
    if (widget.crossFadeState == CrossFadeState.showSecond)
242
      _controller.value = 1.0;
243 244
    _firstAnimation = _initAnimation(widget.firstCurve, true);
    _secondAnimation = _initAnimation(widget.secondCurve, false);
245 246
  }

247
  Animation<double> _initAnimation(Curve curve, bool inverted) {
248
    Animation<double> animation = new CurvedAnimation(
249
      parent: _controller,
250
      curve: curve,
251 252
    );

253 254
    if (inverted) {
      animation = new Tween<double>(
255 256
        begin: 1.0,
        end: 0.0,
257 258 259 260 261 262 263 264 265 266 267
      ).animate(animation);
    }

    animation.addStatusListener((AnimationStatus status) {
      setState(() {
        // Trigger a rebuild because it depends on _isTransitioning, which
        // changes its value together with animation status.
      });
    });

    return animation;
268 269 270 271 272 273 274 275 276
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
277 278 279 280 281 282 283 284 285 286
  void didUpdateWidget(AnimatedCrossFade oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.duration != oldWidget.duration)
      _controller.duration = widget.duration;
    if (widget.firstCurve != oldWidget.firstCurve)
      _firstAnimation = _initAnimation(widget.firstCurve, true);
    if (widget.secondCurve != oldWidget.secondCurve)
      _secondAnimation = _initAnimation(widget.secondCurve, false);
    if (widget.crossFadeState != oldWidget.crossFadeState) {
      switch (widget.crossFadeState) {
287 288 289 290 291 292 293 294 295 296
        case CrossFadeState.showFirst:
          _controller.reverse();
          break;
        case CrossFadeState.showSecond:
          _controller.forward();
          break;
      }
    }
  }

297 298
  /// Whether we're in the middle of cross-fading this frame.
  bool get _isTransitioning => _controller.status == AnimationStatus.forward || _controller.status == AnimationStatus.reverse;
299

300 301
  @override
  Widget build(BuildContext context) {
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    const Key kFirstChildKey = const ValueKey<CrossFadeState>(CrossFadeState.showFirst);
    const Key kSecondChildKey = const ValueKey<CrossFadeState>(CrossFadeState.showSecond);
    final bool transitioningForwards = _controller.status == AnimationStatus.completed || _controller.status == AnimationStatus.forward;

    Key topKey;
    Widget topChild;
    Animation<double> topAnimation;
    Key bottomKey;
    Widget bottomChild;
    Animation<double> bottomAnimation;
    if (transitioningForwards) {
      topKey = kSecondChildKey;
      topChild = widget.secondChild;
      topAnimation = _secondAnimation;
      bottomKey = kFirstChildKey;
      bottomChild = widget.firstChild;
      bottomAnimation = _firstAnimation;
    } else {
      topKey = kFirstChildKey;
      topChild = widget.firstChild;
      topAnimation = _firstAnimation;
      bottomKey = kSecondChildKey;
      bottomChild = widget.secondChild;
      bottomAnimation = _secondAnimation;
    }

328 329 330 331 332 333 334 335
    bottomChild = new TickerMode(
      key: bottomKey,
      enabled: _isTransitioning,
      child: new ExcludeSemantics(
        excluding: true, // Always exclude the semantics of the widget that's fading out.
        child: new FadeTransition(
          opacity: bottomAnimation,
          child: bottomChild,
336
        ),
337
      ),
338 339 340 341 342 343 344 345 346
    );
    topChild = new TickerMode(
      key: topKey,
      enabled: true, // Top widget always has its animations enabled.
      child: new ExcludeSemantics(
        excluding: false, // Always publish semantics for the widget that's fading in.
        child: new FadeTransition(
          opacity: topAnimation,
          child: topChild,
347
        ),
348
      ),
349
    );
350 351
    return new ClipRect(
      child: new AnimatedSize(
352
        alignment: widget.alignment,
353 354
        duration: widget.duration,
        curve: widget.sizeCurve,
355
        vsync: this,
356
        child: widget.layoutBuilder(topChild, topKey, bottomChild, bottomKey),
357
      ),
358 359
    );
  }
360 361

  @override
362
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
363 364 365
    super.debugFillProperties(description);
    description.add(new EnumProperty<CrossFadeState>('crossFadeState', widget.crossFadeState));
    description.add(new DiagnosticsProperty<AnimationController>('controller', _controller, showName: false));
366
    description.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', widget.alignment, defaultValue: Alignment.topCenter));
367
  }
368
}