animated_size.dart 11.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

import 'box.dart';
9
import 'layer.dart';
10 11 12
import 'object.dart';
import 'shifted_box.dart';

13 14 15 16 17 18
/// A [RenderAnimatedSize] can be in exactly one of these states.
@visibleForTesting
enum RenderAnimatedSizeState {
  /// The initial state, when we do not yet know what the starting and target
  /// sizes are to animate.
  ///
19
  /// The next state is [stable].
20 21 22 23 24
  start,

  /// At this state the child's size is assumed to be stable and we are either
  /// animating, or waiting for the child's size to change.
  ///
25 26
  /// If the child's size changes, the state will become [changed]. Otherwise,
  /// it remains [stable].
27 28 29 30 31
  stable,

  /// At this state we know that the child has changed once after being assumed
  /// [stable].
  ///
32
  /// The next state will be one of:
33
  ///
34 35 36 37 38
  /// * [stable] if the child's size stabilized immediately. This is a signal
  ///   for the render object to begin animating the size towards the child's new
  ///   size.
  ///
  /// * [unstable] if the child's size continues to change.
39 40
  changed,

41 42
  /// At this state the child's size is assumed to be unstable (changing each
  /// frame).
43
  ///
44 45
  /// Instead of chasing the child's size in this state, the render object
  /// tightly tracks the child's size until it stabilizes.
46
  ///
47 48 49
  /// The render object remains in this state until a frame where the child's
  /// size remains the same as the previous frame. At that time, the next state
  /// is [stable].
50 51 52
  unstable,
}

53
/// A render object that animates its size to its child's size over a given
54 55 56 57 58
/// [duration] and with a given [curve]. If the child's size itself animates
/// (i.e. if it changes size two frames in a row, as opposed to abruptly
/// changing size in one frame then remaining that size in subsequent frames),
/// this render object sizes itself to fit the child instead of animating
/// itself.
59
///
60 61
/// When the child overflows the current animated size of this render object, it
/// is clipped.
62 63
class RenderAnimatedSize extends RenderAligningShiftedBox {
  /// Creates a render object that animates its size to match its child.
64 65 66
  /// The [duration] and [curve] arguments define the animation.
  ///
  /// The [alignment] argument is used to align the child when the parent is not
67 68
  /// (yet) the same size as the child.
  ///
69 70 71 72 73 74 75
  /// The [duration] is required.
  ///
  /// The [vsync] should specify a [TickerProvider] for the animation
  /// controller.
  ///
  /// The arguments [duration], [curve], [alignment], and [vsync] must
  /// not be null.
76
  RenderAnimatedSize({
77 78 79
    required TickerProvider vsync,
    required Duration duration,
    Duration? reverseDuration,
80
    Curve curve = Curves.linear,
81 82 83
    super.alignment,
    super.textDirection,
    super.child,
84
    Clip clipBehavior = Clip.hardEdge,
85 86 87
  }) : assert(vsync != null),
       assert(duration != null),
       assert(curve != null),
88
       assert(clipBehavior != null),
89
       _vsync = vsync,
90
       _clipBehavior = clipBehavior {
91
    _controller = AnimationController(
92 93
      vsync: vsync,
      duration: duration,
94
      reverseDuration: reverseDuration,
95
    )..addListener(() {
96
      if (_controller.value != _lastValue) {
97
        markNeedsLayout();
98
      }
99
    });
100
    _animation = CurvedAnimation(
101
      parent: _controller,
102
      curve: curve,
103 104 105
    );
  }

106 107
  late final AnimationController _controller;
  late final CurvedAnimation _animation;
108
  final SizeTween _sizeTween = SizeTween();
109 110
  late bool _hasVisualOverflow;
  double? _lastValue;
111

112 113 114 115 116 117 118
  /// The state this size animation is in.
  ///
  /// See [RenderAnimatedSizeState] for possible states.
  @visibleForTesting
  RenderAnimatedSizeState get state => _state;
  RenderAnimatedSizeState _state = RenderAnimatedSizeState.start;

119
  /// The duration of the animation.
120
  Duration get duration => _controller.duration!;
121 122
  set duration(Duration value) {
    assert(value != null);
123
    if (value == _controller.duration) {
124
      return;
125
    }
126 127 128
    _controller.duration = value;
  }

129
  /// The duration of the animation when running in reverse.
130 131
  Duration? get reverseDuration => _controller.reverseDuration;
  set reverseDuration(Duration? value) {
132
    if (value == _controller.reverseDuration) {
133
      return;
134
    }
135 136 137
    _controller.reverseDuration = value;
  }

138 139 140 141
  /// The curve of the animation.
  Curve get curve => _animation.curve;
  set curve(Curve value) {
    assert(value != null);
142
    if (value == _animation.curve) {
143
      return;
144
    }
145 146 147
    _animation.curve = value;
  }

148
  /// {@macro flutter.material.Material.clipBehavior}
149 150 151 152 153 154 155 156 157 158 159 160 161
  ///
  /// Defaults to [Clip.hardEdge], and must not be null.
  Clip get clipBehavior => _clipBehavior;
  Clip _clipBehavior = Clip.hardEdge;
  set clipBehavior(Clip value) {
    assert(value != null);
    if (value != _clipBehavior) {
      _clipBehavior = value;
      markNeedsPaint();
      markNeedsSemanticsUpdate();
    }
  }

162 163 164 165 166 167
  /// Whether the size is being currently animated towards the child's size.
  ///
  /// See [RenderAnimatedSizeState] for situations when we may not be animating
  /// the size.
  bool get isAnimating => _controller.isAnimating;

168 169 170 171 172
  /// The [TickerProvider] for the [AnimationController] that runs the animation.
  TickerProvider get vsync => _vsync;
  TickerProvider _vsync;
  set vsync(TickerProvider value) {
    assert(value != null);
173
    if (value == _vsync) {
174
      return;
175
    }
176 177 178 179
    _vsync = value;
    _controller.resync(vsync);
  }

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    switch (state) {
      case RenderAnimatedSizeState.start:
      case RenderAnimatedSizeState.stable:
        break;
      case RenderAnimatedSizeState.changed:
      case RenderAnimatedSizeState.unstable:
        // Call markNeedsLayout in case the RenderObject isn't marked dirty
        // already, to resume interrupted resizing animation.
        markNeedsLayout();
        break;
    }
  }

196 197 198 199 200 201
  @override
  void detach() {
    _controller.stop();
    super.detach();
  }

202
  Size? get _animatedSize {
203 204 205 206 207 208 209
    return _sizeTween.evaluate(_animation);
  }

  @override
  void performLayout() {
    _lastValue = _controller.value;
    _hasVisualOverflow = false;
210
    final BoxConstraints constraints = this.constraints;
211 212
    if (child == null || constraints.isTight) {
      _controller.stop();
213
      size = _sizeTween.begin = _sizeTween.end = constraints.smallest;
214 215
      _state = RenderAnimatedSizeState.start;
      child?.layout(constraints);
216 217 218
      return;
    }

219
    child!.layout(constraints, parentUsesSize: true);
220

221 222
    assert(_state != null);
    switch (_state) {
223 224 225 226 227 228 229 230 231 232 233 234
      case RenderAnimatedSizeState.start:
        _layoutStart();
        break;
      case RenderAnimatedSizeState.stable:
        _layoutStable();
        break;
      case RenderAnimatedSizeState.changed:
        _layoutChanged();
        break;
      case RenderAnimatedSizeState.unstable:
        _layoutUnstable();
        break;
235 236
    }

237
    size = constraints.constrain(_animatedSize!);
238 239
    alignChild();

240
    if (size.width < _sizeTween.end!.width ||
241
        size.height < _sizeTween.end!.height) {
242
      _hasVisualOverflow = true;
243
    }
244 245
  }

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    if (child == null || constraints.isTight) {
      return constraints.smallest;
    }

    // This simplified version of performLayout only calculates the current
    // size without modifying global state. See performLayout for comments
    // explaining the rational behind the implementation.
    final Size childSize = child!.getDryLayout(constraints);
    assert(_state != null);
    switch (_state) {
      case RenderAnimatedSizeState.start:
        return constraints.constrain(childSize);
      case RenderAnimatedSizeState.stable:
        if (_sizeTween.end != childSize) {
          return constraints.constrain(size);
        } else if (_controller.value == _controller.upperBound) {
          return constraints.constrain(childSize);
        }
        break;
      case RenderAnimatedSizeState.unstable:
      case RenderAnimatedSizeState.changed:
        if (_sizeTween.end != childSize) {
          return constraints.constrain(childSize);
        }
        break;
    }

    return constraints.constrain(_animatedSize!);
  }

278 279 280 281 282 283 284 285 286 287
  void _restartAnimation() {
    _lastValue = 0.0;
    _controller.forward(from: 0.0);
  }

  /// Laying out the child for the first time.
  ///
  /// We have the initial size to animate from, but we do not have the target
  /// size to animate to, so we set both ends to child's size.
  void _layoutStart() {
288
    _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
289 290 291 292 293 294 295 296 297
    _state = RenderAnimatedSizeState.stable;
  }

  /// At this state we're assuming the child size is stable and letting the
  /// animation run its course.
  ///
  /// If during animation the size of the child changes we restart the
  /// animation.
  void _layoutStable() {
298
    if (_sizeTween.end != child!.size) {
299
      _sizeTween.begin = size;
300
      _sizeTween.end = debugAdoptSize(child!.size);
301 302 303 304
      _restartAnimation();
      _state = RenderAnimatedSizeState.changed;
    } else if (_controller.value == _controller.upperBound) {
      // Animation finished. Reset target sizes.
305
      _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
306 307
    } else if (!_controller.isAnimating) {
      _controller.forward(); // resume the animation after being detached
308 309 310 311 312 313 314 315 316 317
    }
  }

  /// This state indicates that the size of the child changed once after being
  /// considered stable.
  ///
  /// If the child stabilizes immediately, we go back to stable state. If it
  /// changes again, we match the child's size, restart animation and go to
  /// unstable state.
  void _layoutChanged() {
318
    if (_sizeTween.end != child!.size) {
319
      // Child size changed again. Match the child's size and restart animation.
320
      _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
321 322 323 324 325
      _restartAnimation();
      _state = RenderAnimatedSizeState.unstable;
    } else {
      // Child size stabilized.
      _state = RenderAnimatedSizeState.stable;
326 327 328 329
      if (!_controller.isAnimating) {
        // Resume the animation after being detached.
        _controller.forward();
      }
330 331 332 333 334 335 336
    }
  }

  /// The child's size is not stable.
  ///
  /// Continue tracking the child's size until is stabilizes.
  void _layoutUnstable() {
337
    if (_sizeTween.end != child!.size) {
338
      // Still unstable. Continue tracking the child.
339
      _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
340 341 342 343 344 345 346 347
      _restartAnimation();
    } else {
      // Child size stabilized.
      _controller.stop();
      _state = RenderAnimatedSizeState.stable;
    }
  }

348 349
  @override
  void paint(PaintingContext context, Offset offset) {
350
    if (child != null && _hasVisualOverflow && clipBehavior != Clip.none) {
351
      final Rect rect = Offset.zero & size;
352
      _clipRectLayer.layer = context.pushClipRect(
353 354 355 356 357
        needsCompositing,
        offset,
        rect,
        super.paint,
        clipBehavior: clipBehavior,
358
        oldLayer: _clipRectLayer.layer,
359
      );
360
    } else {
361
      _clipRectLayer.layer = null;
362 363 364
      super.paint(context, offset);
    }
  }
365

366 367 368 369 370 371 372
  final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();

  @override
  void dispose() {
    _clipRectLayer.layer = null;
    super.dispose();
  }
373
}