scaffold.dart 79.3 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

Hixie's avatar
Hixie committed
5 6
import 'dart:async';
import 'dart:collection';
7
import 'dart:math' as math;
8

9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/rendering.dart';
11
import 'package:flutter/scheduler.dart';
12
import 'package:flutter/widgets.dart';
13
import 'package:flutter/gestures.dart' show DragStartBehavior;
14

15
import 'app_bar.dart';
16
import 'bottom_sheet.dart';
17
import 'button_bar.dart';
18
import 'button_theme.dart';
19
import 'divider.dart';
20
import 'drawer.dart';
21
import 'flexible_space_bar.dart';
22
import 'floating_action_button.dart';
23
import 'floating_action_button_location.dart';
24
import 'material.dart';
Hixie's avatar
Hixie committed
25
import 'snack_bar.dart';
26
import 'theme.dart';
27

28
// Examples can assume:
29
// TabController tabController;
30
// void setState(VoidCallback fn) { }
31 32 33
// String appBarTitle;
// int tabCount;
// TickerProvider tickerProvider;
34

35 36
const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation = FloatingActionButtonLocation.endFloat;
const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = FloatingActionButtonAnimator.scaling;
37

38
enum _ScaffoldSlot {
39
  body,
40
  appBar,
41 42
  bottomSheet,
  snackBar,
43
  persistentFooter,
44
  bottomNavigationBar,
45 46
  floatingActionButton,
  drawer,
47
  endDrawer,
48
  statusBar,
49
}
Hans Muller's avatar
Hans Muller committed
50

51 52
/// The geometry of the [Scaffold] after all its contents have been laid out
/// except the [FloatingActionButton].
53
///
54
/// The [Scaffold] passes this pre-layout geometry to its
55
/// [FloatingActionButtonLocation], which produces an [Offset] that the
56
/// [Scaffold] uses to position the [FloatingActionButton].
57
///
58 59 60 61 62 63 64
/// For a description of the [Scaffold]'s geometry after it has
/// finished laying out, see the [ScaffoldGeometry].
@immutable
class ScaffoldPrelayoutGeometry {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ScaffoldPrelayoutGeometry({
65 66 67 68 69 70 71
    @required this.bottomSheetSize,
    @required this.contentBottom,
    @required this.contentTop,
    @required this.floatingActionButtonSize,
    @required this.minInsets,
    @required this.scaffoldSize,
    @required this.snackBarSize,
72 73 74 75
    @required this.textDirection,
  });

  /// The [Size] of [Scaffold.floatingActionButton].
76
  ///
77 78 79 80
  /// If [Scaffold.floatingActionButton] is null, this will be [Size.zero].
  final Size floatingActionButtonSize;

  /// The [Size] of the [Scaffold]'s [BottomSheet].
81
  ///
82 83 84 85 86 87
  /// If the [Scaffold] is not currently showing a [BottomSheet],
  /// this will be [Size.zero].
  final Size bottomSheetSize;

  /// The vertical distance from the Scaffold's origin to the bottom of
  /// [Scaffold.body].
88
  ///
89 90 91 92
  /// This is useful in a [FloatingActionButtonLocation] designed to
  /// place the [FloatingActionButton] at the bottom of the screen, while
  /// keeping it above the [BottomSheet], the [Scaffold.bottomNavigationBar],
  /// or the keyboard.
93
  ///
Ian Hickson's avatar
Ian Hickson committed
94 95 96 97
  /// The [Scaffold.body] is laid out with respect to [minInsets] already. This
  /// means that a [FloatingActionButtonLocation] does not need to factor in
  /// [minInsets.bottom] when aligning a [FloatingActionButton] to
  /// [contentBottom].
98 99 100 101
  final double contentBottom;

  /// The vertical distance from the [Scaffold]'s origin to the top of
  /// [Scaffold.body].
102
  ///
103 104 105
  /// This is useful in a [FloatingActionButtonLocation] designed to
  /// place the [FloatingActionButton] at the top of the screen, while
  /// keeping it below the [Scaffold.appBar].
106
  ///
Ian Hickson's avatar
Ian Hickson committed
107 108 109
  /// The [Scaffold.body] is laid out with respect to [minInsets] already. This
  /// means that a [FloatingActionButtonLocation] does not need to factor in
  /// [minInsets.top] when aligning a [FloatingActionButton] to [contentTop].
110 111 112 113
  final double contentTop;

  /// The minimum padding to inset the [FloatingActionButton] by for it
  /// to remain visible.
114
  ///
115 116 117 118
  /// This value is the result of calling [MediaQuery.padding] in the
  /// [Scaffold]'s [BuildContext],
  /// and is useful for insetting the [FloatingActionButton] to avoid features like
  /// the system status bar or the keyboard.
119
  ///
120 121
  /// If [Scaffold.resizeToAvoidBottomInset] is set to false, [minInsets.bottom]
  /// will be 0.0.
122 123 124
  final EdgeInsets minInsets;

  /// The [Size] of the whole [Scaffold].
125 126
  ///
  /// If the [Size] of the [Scaffold]'s contents is modified by values such as
127
  /// [Scaffold.resizeToAvoidBottomInset] or the keyboard opening, then the
128
  /// [scaffoldSize] will not reflect those changes.
129
  ///
130 131 132 133
  /// This means that [FloatingActionButtonLocation]s designed to reposition
  /// the [FloatingActionButton] based on events such as the keyboard popping
  /// up should use [minInsets] to make sure that the [FloatingActionButton] is
  /// inset by enough to remain visible.
134
  ///
135 136 137 138 139
  /// See [minInsets] and [MediaQuery.padding] for more information on the appropriate
  /// insets to apply.
  final Size scaffoldSize;

  /// The [Size] of the [Scaffold]'s [SnackBar].
140
  ///
141 142 143 144 145 146 147 148 149 150 151 152 153
  /// If the [Scaffold] is not showing a [SnackBar], this will be [Size.zero].
  final Size snackBarSize;

  /// The [TextDirection] of the [Scaffold]'s [BuildContext].
  final TextDirection textDirection;
}

/// A snapshot of a transition between two [FloatingActionButtonLocation]s.
///
/// [ScaffoldState] uses this to seamlessly change transition animations
/// when a running [FloatingActionButtonLocation] transition is interrupted by a new transition.
@immutable
class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation {
154

155 156 157 158 159 160 161 162 163 164
  const _TransitionSnapshotFabLocation(this.begin, this.end, this.animator, this.progress);

  final FloatingActionButtonLocation begin;
  final FloatingActionButtonLocation end;
  final FloatingActionButtonAnimator animator;
  final double progress;

  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    return animator.getOffset(
165 166
      begin: begin.getOffset(scaffoldGeometry),
      end: end.getOffset(scaffoldGeometry),
167 168 169 170 171 172 173 174 175 176 177
      progress: progress,
    );
  }

  @override
  String toString() {
    return '$runtimeType(begin: $begin, end: $end, progress: $progress)';
  }
}

/// Geometry information for [Scaffold] components after layout is finished.
178
///
179 180
/// To get a [ValueNotifier] for the scaffold geometry of a given
/// [BuildContext], use [Scaffold.geometryOf].
181
///
182 183
/// The ScaffoldGeometry is only available during the paint phase, because
/// its value is computed during the animation and layout phases prior to painting.
184
///
185 186 187
/// For an example of using the [ScaffoldGeometry], see the [BottomAppBar],
/// which uses the [ScaffoldGeometry] to paint a notch around the
/// [FloatingActionButton].
188 189
///
/// For information about the [Scaffold]'s geometry that is used while laying
190
/// out the [FloatingActionButton], see [ScaffoldPrelayoutGeometry].
191 192
@immutable
class ScaffoldGeometry {
193
  /// Create an object that describes the geometry of a [Scaffold].
194 195 196 197 198
  const ScaffoldGeometry({
    this.bottomNavigationBarTop,
    this.floatingActionButtonArea,
  });

199 200
  /// The distance from the [Scaffold]'s top edge to the top edge of the
  /// rectangle in which the [Scaffold.bottomNavigationBar] bar is laid out.
201
  ///
202
  /// Null if [Scaffold.bottomNavigationBar] is null.
203 204
  final double bottomNavigationBarTop;

205
  /// The [Scaffold.floatingActionButton]'s bounding rectangle.
206 207 208 209
  ///
  /// This is null when there is no floating action button showing.
  final Rect floatingActionButtonArea;

210
  ScaffoldGeometry _scaleFloatingActionButton(double scaleFactor) {
211 212 213
    if (scaleFactor == 1.0)
      return this;

214
    if (scaleFactor == 0.0) {
215
      return ScaffoldGeometry(
216 217 218
        bottomNavigationBarTop: bottomNavigationBarTop,
      );
    }
219

220
    final Rect scaledButton = Rect.lerp(
221 222
      floatingActionButtonArea.center & Size.zero,
      floatingActionButtonArea,
223
      scaleFactor,
224
    );
225 226 227 228 229 230 231 232 233
    return copyWith(floatingActionButtonArea: scaledButton);
  }

  /// Creates a copy of this [ScaffoldGeometry] but with the given fields replaced with
  /// the new values.
  ScaffoldGeometry copyWith({
    double bottomNavigationBarTop,
    Rect floatingActionButtonArea,
  }) {
234
    return ScaffoldGeometry(
235 236
      bottomNavigationBarTop: bottomNavigationBarTop ?? this.bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonArea ?? this.floatingActionButtonArea,
237 238
    );
  }
239 240
}

241 242 243
class _ScaffoldGeometryNotifier extends ChangeNotifier implements ValueListenable<ScaffoldGeometry> {
  _ScaffoldGeometryNotifier(this.geometry, this.context)
    : assert (context != null);
244 245

  final BuildContext context;
246
  double floatingActionButtonScale;
247
  ScaffoldGeometry geometry;
248 249 250 251 252 253

  @override
  ScaffoldGeometry get value {
    assert(() {
      final RenderObject renderObject = context.findRenderObject();
      if (renderObject == null || !renderObject.owner.debugDoingPaint)
254
        throw FlutterError(
255 256 257 258 259 260
            'Scaffold.geometryOf() must only be accessed during the paint phase.\n'
            'The ScaffoldGeometry is only available during the paint phase, because\n'
            'its value is computed during the animation and layout phases prior to painting.'
        );
      return true;
    }());
261
    return geometry._scaleFloatingActionButton(floatingActionButtonScale);
262 263 264 265 266 267 268
  }

  void _updateWith({
    double bottomNavigationBarTop,
    Rect floatingActionButtonArea,
    double floatingActionButtonScale,
  }) {
269
    this.floatingActionButtonScale = floatingActionButtonScale ?? this.floatingActionButtonScale;
270 271 272
    geometry = geometry.copyWith(
      bottomNavigationBarTop: bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonArea,
273
    );
274
    notifyListeners();
275 276 277
  }
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
// Used to communicate the height of the Scaffold's bottomNavigationBar and
// persistentFooterButtons to the LayoutBuilder which builds the Scaffold's body.
//
// Scaffold expects a _BodyBoxConstraints to be passed to the _BodyBuilder
// widget's LayoutBuilder, see _ScaffoldLayout.performLayout(). The BoxConstraints
// methods that construct new BoxConstraints objects, like copyWith() have not
// been overridden here because we expect the _BodyBoxConstraintsObject to be
// passed along unmodified to the LayoutBuilder. If that changes in the future
// then _BodyBuilder will assert.
class _BodyBoxConstraints extends BoxConstraints {
  const _BodyBoxConstraints({
    double minWidth = 0.0,
    double maxWidth = double.infinity,
    double minHeight = 0.0,
    double maxHeight = double.infinity,
    @required this.bottomWidgetsHeight,
  }) :  assert(bottomWidgetsHeight != null),
        assert(bottomWidgetsHeight >= 0),
        super(minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight);

  final double bottomWidgetsHeight;

  // RenderObject.layout() will only short-circuit its call to its performLayout
  // method if the new layout constraints are not == to the current constraints.
  // If the height of the bottom widgets has changed, even though the constraints'
  // min and max values have not, we still want performLayout to happen.
  @override
  bool operator ==(dynamic other) {
    if (super != other)
      return false;
    final _BodyBoxConstraints typedOther = other;
    return bottomWidgetsHeight == typedOther.bottomWidgetsHeight;
  }

  @override
  int get hashCode {
    return hashValues(super.hashCode, bottomWidgetsHeight);
  }
}

// Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery
// whose padding accounts for the height of the bottomNavigationBar and/or the
// persistentFooterButtons.
//
// The bottom widgets' height is passed along via the _BodyBoxConstraints parameter.
// The constraints parameter is constructed in_ScaffoldLayout.performLayout().
class _BodyBuilder extends StatelessWidget {
  const _BodyBuilder({ Key key, this.body }) : super(key: key);

  final Widget body;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final _BodyBoxConstraints bodyConstraints = constraints;
        final MediaQueryData metrics = MediaQuery.of(context);
        return MediaQuery(
          data: metrics.copyWith(
            padding: metrics.padding.copyWith(
              bottom: math.max(metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight),
            ),
          ),
          child: body,
        );
      },
    );
  }
}

348
class _ScaffoldLayout extends MultiChildLayoutDelegate {
349
  _ScaffoldLayout({
350
    @required this.minInsets,
351
    @required this.textDirection,
352
    @required this.geometryNotifier,
353 354 355 356 357
    // for floating action button
    @required this.previousFloatingActionButtonLocation,
    @required this.currentFloatingActionButtonLocation,
    @required this.floatingActionButtonMoveAnimationProgress,
    @required this.floatingActionButtonMotionAnimator,
358
    @required this.extendBody,
359 360 361 362
  }) : assert(minInsets != null),
       assert(textDirection != null),
       assert(geometryNotifier != null),
       assert(previousFloatingActionButtonLocation != null),
363 364
       assert(currentFloatingActionButtonLocation != null),
       assert(extendBody != null);
365

366
  final bool extendBody;
367
  final EdgeInsets minInsets;
368
  final TextDirection textDirection;
369
  final _ScaffoldGeometryNotifier geometryNotifier;
370

371 372 373 374 375
  final FloatingActionButtonLocation previousFloatingActionButtonLocation;
  final FloatingActionButtonLocation currentFloatingActionButtonLocation;
  final double floatingActionButtonMoveAnimationProgress;
  final FloatingActionButtonAnimator floatingActionButtonMotionAnimator;

376
  @override
377
  void performLayout(Size size) {
378
    final BoxConstraints looseConstraints = BoxConstraints.loose(size);
379

380
    // This part of the layout has the same effect as putting the app bar and
381
    // body in a column and making the body flexible. What's different is that
382
    // in this case the app bar appears _after_ the body in the stacking order,
383
    // so the app bar's shadow is drawn on top of the body.
384

385
    final BoxConstraints fullWidthConstraints = looseConstraints.tighten(width: size.width);
386
    final double bottom = size.height;
387
    double contentTop = 0.0;
388
    double bottomWidgetsHeight = 0.0;
389

390
    if (hasChild(_ScaffoldSlot.appBar)) {
391
      contentTop = layoutChild(_ScaffoldSlot.appBar, fullWidthConstraints).height;
392
      positionChild(_ScaffoldSlot.appBar, Offset.zero);
393 394
    }

395
    double bottomNavigationBarTop;
396 397
    if (hasChild(_ScaffoldSlot.bottomNavigationBar)) {
      final double bottomNavigationBarHeight = layoutChild(_ScaffoldSlot.bottomNavigationBar, fullWidthConstraints).height;
398
      bottomWidgetsHeight += bottomNavigationBarHeight;
399
      bottomNavigationBarTop = math.max(0.0, bottom - bottomWidgetsHeight);
400
      positionChild(_ScaffoldSlot.bottomNavigationBar, Offset(0.0, bottomNavigationBarTop));
401 402
    }

403
    if (hasChild(_ScaffoldSlot.persistentFooter)) {
404
      final BoxConstraints footerConstraints = BoxConstraints(
Ian Hickson's avatar
Ian Hickson committed
405
        maxWidth: fullWidthConstraints.maxWidth,
406
        maxHeight: math.max(0.0, bottom - bottomWidgetsHeight - contentTop),
Ian Hickson's avatar
Ian Hickson committed
407 408
      );
      final double persistentFooterHeight = layoutChild(_ScaffoldSlot.persistentFooter, footerConstraints).height;
409
      bottomWidgetsHeight += persistentFooterHeight;
410
      positionChild(_ScaffoldSlot.persistentFooter, Offset(0.0, math.max(0.0, bottom - bottomWidgetsHeight)));
411 412
    }

413 414 415
    // Set the content bottom to account for the greater of the height of any
    // bottom-anchored material widgets or of the keyboard or other
    // bottom-anchored system UI.
416
    final double contentBottom = math.max(0.0, bottom - math.max(minInsets.bottom, bottomWidgetsHeight));
417

418
    if (hasChild(_ScaffoldSlot.body)) {
419 420 421 422 423 424 425 426
      double bodyMaxHeight = math.max(0.0, contentBottom - contentTop);

      if (extendBody) {
        bodyMaxHeight += bottomWidgetsHeight;
        assert(bodyMaxHeight <= math.max(0.0, looseConstraints.maxHeight - contentTop));
      }

      final BoxConstraints bodyConstraints = _BodyBoxConstraints(
427
        maxWidth: fullWidthConstraints.maxWidth,
428 429
        maxHeight: bodyMaxHeight,
        bottomWidgetsHeight: extendBody ? bottomWidgetsHeight : 0.0,
430
      );
431
      layoutChild(_ScaffoldSlot.body, bodyConstraints);
432
      positionChild(_ScaffoldSlot.body, Offset(0.0, contentTop));
433
    }
434 435

    // The BottomSheet and the SnackBar are anchored to the bottom of the parent,
436 437 438 439
    // they're as wide as the parent and are given their intrinsic height. The
    // only difference is that SnackBar appears on the top side of the
    // BottomNavigationBar while the BottomSheet is stacked on top of it.
    //
440 441
    // If all three elements are present then either the center of the FAB straddles
    // the top edge of the BottomSheet or the bottom of the FAB is
442
    // kFloatingActionButtonMargin above the SnackBar, whichever puts the FAB
443 444
    // the farthest above the bottom of the parent. If only the FAB is has a
    // non-zero height then it's inset from the parent's right and bottom edges
445
    // by kFloatingActionButtonMargin.
446

447 448 449
    Size bottomSheetSize = Size.zero;
    Size snackBarSize = Size.zero;

450
    if (hasChild(_ScaffoldSlot.bottomSheet)) {
451
      final BoxConstraints bottomSheetConstraints = BoxConstraints(
Ian Hickson's avatar
Ian Hickson committed
452 453 454 455
        maxWidth: fullWidthConstraints.maxWidth,
        maxHeight: math.max(0.0, contentBottom - contentTop),
      );
      bottomSheetSize = layoutChild(_ScaffoldSlot.bottomSheet, bottomSheetConstraints);
456
      positionChild(_ScaffoldSlot.bottomSheet, Offset((size.width - bottomSheetSize.width) / 2.0, contentBottom - bottomSheetSize.height));
457 458
    }

459
    if (hasChild(_ScaffoldSlot.snackBar)) {
460
      snackBarSize = layoutChild(_ScaffoldSlot.snackBar, fullWidthConstraints);
461
      positionChild(_ScaffoldSlot.snackBar, Offset(0.0, contentBottom - snackBarSize.height));
462 463
    }

464
    Rect floatingActionButtonRect;
465
    if (hasChild(_ScaffoldSlot.floatingActionButton)) {
466
      final Size fabSize = layoutChild(_ScaffoldSlot.floatingActionButton, looseConstraints);
467

468 469
      // To account for the FAB position being changed, we'll animate between
      // the old and new positions.
470
      final ScaffoldPrelayoutGeometry currentGeometry = ScaffoldPrelayoutGeometry(
471 472 473 474 475 476 477 478 479 480 481 482
        bottomSheetSize: bottomSheetSize,
        contentBottom: contentBottom,
        contentTop: contentTop,
        floatingActionButtonSize: fabSize,
        minInsets: minInsets,
        scaffoldSize: size,
        snackBarSize: snackBarSize,
        textDirection: textDirection,
      );
      final Offset currentFabOffset = currentFloatingActionButtonLocation.getOffset(currentGeometry);
      final Offset previousFabOffset = previousFloatingActionButtonLocation.getOffset(currentGeometry);
      final Offset fabOffset = floatingActionButtonMotionAnimator.getOffset(
483 484
        begin: previousFabOffset,
        end: currentFabOffset,
485 486 487 488
        progress: floatingActionButtonMoveAnimationProgress,
      );
      positionChild(_ScaffoldSlot.floatingActionButton, fabOffset);
      floatingActionButtonRect = fabOffset & fabSize;
489
    }
490

491
    if (hasChild(_ScaffoldSlot.statusBar)) {
492
      layoutChild(_ScaffoldSlot.statusBar, fullWidthConstraints.tighten(height: minInsets.top));
493 494 495
      positionChild(_ScaffoldSlot.statusBar, Offset.zero);
    }

496
    if (hasChild(_ScaffoldSlot.drawer)) {
497
      layoutChild(_ScaffoldSlot.drawer, BoxConstraints.tight(size));
498
      positionChild(_ScaffoldSlot.drawer, Offset.zero);
499
    }
500 501

    if (hasChild(_ScaffoldSlot.endDrawer)) {
502
      layoutChild(_ScaffoldSlot.endDrawer, BoxConstraints.tight(size));
503 504
      positionChild(_ScaffoldSlot.endDrawer, Offset.zero);
    }
505 506 507 508 509

    geometryNotifier._updateWith(
      bottomNavigationBarTop: bottomNavigationBarTop,
      floatingActionButtonArea: floatingActionButtonRect,
    );
Hans Muller's avatar
Hans Muller committed
510
  }
511

512
  @override
513
  bool shouldRelayout(_ScaffoldLayout oldDelegate) {
514 515 516 517 518
    return oldDelegate.minInsets != minInsets
        || oldDelegate.textDirection != textDirection
        || oldDelegate.floatingActionButtonMoveAnimationProgress != floatingActionButtonMoveAnimationProgress
        || oldDelegate.previousFloatingActionButtonLocation != previousFloatingActionButtonLocation
        || oldDelegate.currentFloatingActionButtonLocation != currentFloatingActionButtonLocation;
519
  }
Hans Muller's avatar
Hans Muller committed
520 521
}

522 523 524
/// Handler for scale and rotation animations in the [FloatingActionButton].
///
/// Currently, there are two types of [FloatingActionButton] animations:
525
///
526 527 528 529
/// * Entrance/Exit animations, which this widget triggers
///   when the [FloatingActionButton] is added, updated, or removed.
/// * Motion animations, which are triggered by the [Scaffold]
///   when its [FloatingActionButtonLocation] is updated.
530
class _FloatingActionButtonTransition extends StatefulWidget {
531
  const _FloatingActionButtonTransition({
532
    Key key,
533 534 535 536
    @required this.child,
    @required this.fabMoveAnimation,
    @required this.fabMotionAnimator,
    @required this.geometryNotifier,
537
  }) : assert(fabMoveAnimation != null),
538 539
       assert(fabMotionAnimator != null),
       super(key: key);
540 541

  final Widget child;
542 543
  final Animation<double> fabMoveAnimation;
  final FloatingActionButtonAnimator fabMotionAnimator;
544
  final _ScaffoldGeometryNotifier geometryNotifier;
545

546
  @override
547
  _FloatingActionButtonTransitionState createState() => _FloatingActionButtonTransitionState();
548 549
}

550
class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTransition> with TickerProviderStateMixin {
551 552
  // The animations applied to the Floating Action Button when it is entering or exiting.
  // Controls the previous widget.child as it exits
553
  AnimationController _previousController;
554 555 556
  Animation<double> _previousScaleAnimation;
  Animation<double> _previousRotationAnimation;
  // Controls the current child widget.child as it exits
557
  AnimationController _currentController;
558 559
  // The animations to run, considering the widget's fabMoveAnimation and the current/previous entrance/exit animations.
  Animation<double> _currentScaleAnimation;
560
  Animation<double> _extendedCurrentScaleAnimation;
561
  Animation<double> _currentRotationAnimation;
562
  Widget _previousChild;
563

564
  @override
565 566
  void initState() {
    super.initState();
567

568
    _previousController = AnimationController(
569
      duration: kFloatingActionButtonSegue,
570
      vsync: this,
571
    )..addStatusListener(_handlePreviousAnimationStatusChanged);
572

573
    _currentController = AnimationController(
574
      duration: kFloatingActionButtonSegue,
575 576
      vsync: this,
    );
577 578

    _updateAnimations();
579

580 581 582
    if (widget.child != null) {
      // If we start out with a child, have the child appear fully visible instead
      // of animating in.
583
      _currentController.value = 1.0;
584 585 586 587 588 589
    }
    else {
      // If we start without a child we update the geometry object with a
      // floating action button scale of 0, as it is not showing on the screen.
      _updateGeometryScale(0.0);
    }
590 591
  }

592
  @override
593
  void dispose() {
594 595
    _previousController.dispose();
    _currentController.dispose();
596 597 598
    super.dispose();
  }

599
  @override
600
  void didUpdateWidget(_FloatingActionButtonTransition oldWidget) {
601
    super.didUpdateWidget(oldWidget);
602 603 604
    final bool oldChildIsNull = oldWidget.child == null;
    final bool newChildIsNull = widget.child == null;
    if (oldChildIsNull == newChildIsNull && oldWidget.child?.key == widget.child?.key)
605
      return;
606
    if (oldWidget.fabMotionAnimator != widget.fabMotionAnimator || oldWidget.fabMoveAnimation != widget.fabMoveAnimation) {
607 608 609
      // Get the right scale and rotation animations to use for this widget.
      _updateAnimations();
    }
610 611
    if (_previousController.status == AnimationStatus.dismissed) {
      final double currentValue = _currentController.value;
612
      if (currentValue == 0.0 || oldWidget.child == null) {
613 614 615
        // The current child hasn't started its entrance animation yet. We can
        // just skip directly to the new child's entrance.
        _previousChild = null;
616
        if (widget.child != null)
617 618 619 620 621
          _currentController.forward();
      } else {
        // Otherwise, we need to copy the state from the current controller to
        // the previous controller and run an exit animation for the previous
        // widget before running the entrance animation for the new child.
622
        _previousChild = oldWidget.child;
623 624 625 626 627 628 629 630
        _previousController
          ..value = currentValue
          ..reverse();
        _currentController.value = 0.0;
      }
    }
  }

631 632 633 634 635
  static final Animatable<double> _entranceTurnTween = Tween<double>(
    begin: 1.0 - kFloatingActionButtonTurnInterval,
    end: 1.0,
  ).chain(CurveTween(curve: Curves.easeIn));

636 637
  void _updateAnimations() {
    // Get the animations for exit and entrance.
638
    final CurvedAnimation previousExitScaleAnimation = CurvedAnimation(
639 640 641
      parent: _previousController,
      curve: Curves.easeIn,
    );
642 643
    final Animation<double> previousExitRotationAnimation = Tween<double>(begin: 1.0, end: 1.0).animate(
      CurvedAnimation(
644 645 646
        parent: _previousController,
        curve: Curves.easeIn,
      ),
647 648
    );

649
    final CurvedAnimation currentEntranceScaleAnimation = CurvedAnimation(
650 651 652
      parent: _currentController,
      curve: Curves.easeIn,
    );
653
    final Animation<double> currentEntranceRotationAnimation = _currentController.drive(_entranceTurnTween);
654 655 656 657

    // Get the animations for when the FAB is moving.
    final Animation<double> moveScaleAnimation = widget.fabMotionAnimator.getScaleAnimation(parent: widget.fabMoveAnimation);
    final Animation<double> moveRotationAnimation = widget.fabMotionAnimator.getRotationAnimation(parent: widget.fabMoveAnimation);
658

659
    // Aggregate the animations.
660 661
    _previousScaleAnimation = AnimationMin<double>(moveScaleAnimation, previousExitScaleAnimation);
    _currentScaleAnimation = AnimationMin<double>(moveScaleAnimation, currentEntranceScaleAnimation);
662
    _extendedCurrentScaleAnimation = _currentScaleAnimation.drive(CurveTween(curve: const Interval(0.0, 0.1)));
663

664 665
    _previousRotationAnimation = TrainHoppingAnimation(previousExitRotationAnimation, moveRotationAnimation);
    _currentRotationAnimation = TrainHoppingAnimation(currentEntranceRotationAnimation, moveRotationAnimation);
666 667 668 669 670 671

    _currentScaleAnimation.addListener(_onProgressChanged);
    _previousScaleAnimation.addListener(_onProgressChanged);
  }

  void _handlePreviousAnimationStatusChanged(AnimationStatus status) {
672 673 674
    setState(() {
      if (status == AnimationStatus.dismissed) {
        assert(_currentController.status == AnimationStatus.dismissed);
675
        if (widget.child != null)
676 677 678
          _currentController.forward();
      }
    });
679 680
  }

681 682 683 684 685 686 687
  bool _isExtendedFloatingActionButton(Widget widget) {
    if (widget is! FloatingActionButton)
      return false;
    final FloatingActionButton fab = widget;
    return fab.isExtended;
  }

688
  @override
689
  Widget build(BuildContext context) {
690
    final List<Widget> children = <Widget>[];
691

692
    if (_previousController.status != AnimationStatus.dismissed) {
693
      if (_isExtendedFloatingActionButton(_previousChild)) {
694
        children.add(FadeTransition(
695 696 697 698
          opacity: _previousScaleAnimation,
          child: _previousChild,
        ));
      } else {
699
        children.add(ScaleTransition(
700
          scale: _previousScaleAnimation,
701
          child: RotationTransition(
702 703 704 705 706 707 708 709
            turns: _previousRotationAnimation,
            child: _previousChild,
          ),
        ));
      }
    }

    if (_isExtendedFloatingActionButton(widget.child)) {
710
      children.add(ScaleTransition(
711
        scale: _extendedCurrentScaleAnimation,
712
        child: FadeTransition(
713 714 715 716 717
          opacity: _currentScaleAnimation,
          child: widget.child,
        ),
      ));
    } else {
718
      children.add(ScaleTransition(
719
        scale: _currentScaleAnimation,
720
        child: RotationTransition(
721 722
          turns: _currentRotationAnimation,
          child: widget.child,
723
        ),
724 725
      ));
    }
726

727
    return Stack(
728 729 730
      alignment: Alignment.centerRight,
      children: children,
    );
731
  }
732 733

  void _onProgressChanged() {
734
    _updateGeometryScale(math.max(_previousScaleAnimation.value, _currentScaleAnimation.value));
735 736 737 738 739 740 741
  }

  void _updateGeometryScale(double scale) {
    widget.geometryNotifier._updateWith(
      floatingActionButtonScale: scale,
    );
  }
742 743
}

744 745
/// Implements the basic material design visual layout structure.
///
746
/// This class provides APIs for showing drawers, snack bars, and bottom sheets.
747
///
748 749 750 751
/// To display a snackbar or a persistent bottom sheet, obtain the
/// [ScaffoldState] for the current [BuildContext] via [Scaffold.of] and use the
/// [ScaffoldState.showSnackBar] and [ScaffoldState.showBottomSheet] functions.
///
752
/// {@tool snippet --template=stateful_widget_material}
753 754 755 756 757 758
/// This example shows a [Scaffold] with an [AppBar], a [BottomAppBar] and a
/// [FloatingActionButton]. The [body] is a [Text] placed in a [Center] in order
/// to center the text within the [Scaffold] and the [FloatingActionButton] is
/// centered and docked within the [BottomAppBar] using
/// [FloatingActionButtonLocation.centerDocked]. The [FloatingActionButton] is
/// connected to a callback that increments a counter.
759 760
///
/// ```dart
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
/// int _count = 0;
///
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
///       title: Text('Sample Code'),
///     ),
///     body: Center(
///       child: Text('You have pressed the button $_count times.'),
///     ),
///     bottomNavigationBar: BottomAppBar(
///       child: Container(height: 50.0,),
///     ),
///     floatingActionButton: FloatingActionButton(
///       onPressed: () => setState(() {
///         _count++;
///       }),
///       tooltip: 'Increment Counter',
///       child: Icon(Icons.add),
///     ),
///     floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
///   );
/// }
784
/// ```
785
/// {@end-tool}
786
///
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
/// ## Scaffold layout, the keyboard, and display "notches"
///
/// The scaffold will expand to fill the available space. That usually
/// means that it will occupy its entire window or device screen. When
/// the device's keyboard appears the Scaffold's ancestor [MediaQuery]
/// widget's [MediaQueryData.viewInsets] changes and the Scaffold will
/// be rebuilt. By default the scaffold's [body] is resized to make
/// room for the keyboard. To prevent the resize set
/// [resizeToAvoidBottomInset] to false. In either case the focused
/// widget will be scrolled into view if it's within a scrollable
/// container.
///
/// The [MediaQueryData.padding] value defines areas that might
/// not be completely visible, like the display "notch" on the iPhone
/// X. The scaffold's [body] is not inset by this padding value
/// although an [appBar] or [bottomNavigationBar] will typically
/// cause the body to avoid the padding. The [SafeArea]
/// widget can be used within the scaffold's body to avoid areas
/// like display notches.
///
/// ## Troubleshooting
///
/// ### Nested Scaffolds
///
/// The Scaffold was designed to be the single top level container for
/// a [MaterialApp] and it's typically not necessary to nest
/// scaffolds. For example in a tabbed UI, where the
/// [bottomNavigationBar] is a [TabBar] and the body is a
/// [TabBarView], you might be tempted to make each tab bar view a
/// scaffold with a differently titled AppBar. It would be better to add a
/// listener to the [TabController] that updates the AppBar.
///
819
/// {@tool sample}
820 821 822 823
/// Add a listener to the app's tab controller so that the [AppBar] title of the
/// app's one and only scaffold is reset each time a new tab is selected.
///
/// ```dart
824
/// TabController(vsync: tickerProvider, length: tabCount)..addListener(() {
825 826 827 828 829 830
///   if (!tabController.indexIsChanging) {
///     setState(() {
///       // Rebuild the enclosing scaffold with a new AppBar title
///       appBarTitle = 'Tab ${tabController.index}';
///     });
///   }
831
/// })
832
/// ```
833
/// {@end-tool}
834 835 836 837 838
///
/// Although there are some use cases, like a presentation app that
/// shows embedded flutter content, where nested scaffolds are
/// appropriate, it's best to avoid nesting scaffolds.
///
839 840
/// See also:
///
841 842
///  * [AppBar], which is a horizontal bar typically shown at the top of an app
///    using the [appBar] property.
843 844
///  * [BottomAppBar], which is a horizontal bar typically shown at the bottom
///    of an app using the [bottomNavigationBar] property.
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
///  * [FloatingActionButton], which is a circular button typically shown in the
///    bottom right corner of the app using the [floatingActionButton] property.
///  * [Drawer], which is a vertical panel that is typically displayed to the
///    left of the body (and often hidden on phones) using the [drawer]
///    property.
///  * [BottomNavigationBar], which is a horizontal array of buttons typically
///    shown along the bottom of the app using the [bottomNavigationBar]
///    property.
///  * [SnackBar], which is a temporary notification typically shown near the
///    bottom of the app using the [ScaffoldState.showSnackBar] method.
///  * [BottomSheet], which is an overlay typically shown near the bottom of the
///    app. A bottom sheet can either be persistent, in which case it is shown
///    using the [ScaffoldState.showBottomSheet] method, or modal, in which case
///    it is shown using the [showModalBottomSheet] function.
///  * [ScaffoldState], which is the state associated with this widget.
860
///  * <https://material.io/design/layout/responsive-layout-grid.html>
861
class Scaffold extends StatefulWidget {
862
  /// Creates a visual scaffold for material design widgets.
863
  const Scaffold({
Adam Barth's avatar
Adam Barth committed
864
    Key key,
865
    this.appBar,
Hixie's avatar
Hixie committed
866
    this.body,
867
    this.floatingActionButton,
868 869
    this.floatingActionButtonLocation,
    this.floatingActionButtonAnimator,
870
    this.persistentFooterButtons,
871
    this.drawer,
872
    this.endDrawer,
873
    this.bottomNavigationBar,
874
    this.bottomSheet,
875
    this.backgroundColor,
876 877
    this.resizeToAvoidBottomPadding,
    this.resizeToAvoidBottomInset,
878
    this.primary = true,
879
    this.drawerDragStartBehavior = DragStartBehavior.start,
880
    this.extendBody = false,
881
  }) : assert(primary != null),
882
       assert(extendBody != null),
883 884
       assert(drawerDragStartBehavior != null),
       super(key: key);
Adam Barth's avatar
Adam Barth committed
885

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
  /// If true, and [bottomNavigationBar] or [persistentFooterButtons]
  /// is specified, then the [body] extends to the bottom of the Scaffold,
  /// instead of only extending to the top of the [bottomNavigationBar]
  /// or the [persistentFooterButtons].
  ///
  /// If true, a [MediaQuery] widget whose bottom padding matches the
  /// the height of the [bottomNavigationBar] will be added above the
  /// scaffold's [body].
  ///
  /// This property is often useful when the [bottomNavigationBar] has
  /// a non-rectangular shape, like [CircularNotchedRectangle], which
  /// adds a [FloatingActionButton] sized notch to the top edge of the bar.
  /// In this case specifying `extendBody: true` ensures that that scaffold's
  /// body will be visible through the bottom navigation bar's notch.
  final bool extendBody;

902
  /// An app bar to display at the top of the scaffold.
903
  final PreferredSizeWidget appBar;
904 905 906

  /// The primary content of the scaffold.
  ///
907 908 909 910 911
  /// Displayed below the [appBar], above the bottom of the ambient
  /// [MediaQuery]'s [MediaQueryData.viewInsets], and behind the
  /// [floatingActionButton] and [drawer]. If [resizeToAvoidBottomInset] is
  /// false then the body is not resized when the onscreen keyboard appears,
  /// i.e. it is not inset by `viewInsets.bottom`.
912
  ///
913 914 915
  /// The widget in the body of the scaffold is positioned at the top-left of
  /// the available space between the app bar and the bottom of the scaffold. To
  /// center this widget instead, consider putting it in a [Center] widget and
916 917
  /// having that be the body. To expand this widget instead, consider
  /// putting it in a [SizedBox.expand].
918 919 920
  ///
  /// If you have a column of widgets that should normally fit on the screen,
  /// but may overflow and would in such cases need to scroll, consider using a
921
  /// [ListView] as the body of the scaffold. This is also a good choice for
922
  /// the case where your body is a scrollable list.
Hixie's avatar
Hixie committed
923
  final Widget body;
924

925
  /// A button displayed floating above [body], in the bottom right corner.
926 927
  ///
  /// Typically a [FloatingActionButton].
Adam Barth's avatar
Adam Barth committed
928
  final Widget floatingActionButton;
929

930
  /// Responsible for determining where the [floatingActionButton] should go.
931
  ///
932 933 934 935
  /// If null, the [ScaffoldState] will use the default location, [FloatingActionButtonLocation.endFloat].
  final FloatingActionButtonLocation floatingActionButtonLocation;

  /// Animator to move the [floatingActionButton] to a new [floatingActionButtonLocation].
936
  ///
937 938 939
  /// If null, the [ScaffoldState] will use the default animator, [FloatingActionButtonAnimator.scaling].
  final FloatingActionButtonAnimator floatingActionButtonAnimator;

940 941 942
  /// A set of buttons that are displayed at the bottom of the scaffold.
  ///
  /// Typically this is a list of [FlatButton] widgets. These buttons are
Ian Hickson's avatar
Ian Hickson committed
943
  /// persistently visible, even if the [body] of the scaffold scrolls.
944 945 946
  ///
  /// These widgets will be wrapped in a [ButtonBar].
  ///
Ian Hickson's avatar
Ian Hickson committed
947 948
  /// The [persistentFooterButtons] are rendered above the
  /// [bottomNavigationBar] but below the [body].
949 950
  final List<Widget> persistentFooterButtons;

951
  /// A panel displayed to the side of the [body], often hidden on mobile
952 953
  /// devices. Swipes in from either left-to-right ([TextDirection.ltr]) or
  /// right-to-left ([TextDirection.rtl])
954
  ///
955 956
  /// In the uncommon case that you wish to open the drawer manually, use the
  /// [ScaffoldState.openDrawer] function.
957 958
  ///
  /// Typically a [Drawer].
959
  final Widget drawer;
960

961 962 963 964 965
  /// A panel displayed to the side of the [body], often hidden on mobile
  /// devices. Swipes in from right-to-left ([TextDirection.ltr]) or
  /// left-to-right ([TextDirection.rtl])
  ///
  /// In the uncommon case that you wish to open the drawer manually, use the
966
  /// [ScaffoldState.openEndDrawer] function.
967 968 969 970
  ///
  /// Typically a [Drawer].
  final Widget endDrawer;

971 972 973 974 975
  /// The color of the [Material] widget that underlies the entire Scaffold.
  ///
  /// The theme's [ThemeData.scaffoldBackgroundColor] by default.
  final Color backgroundColor;

976 977
  /// A bottom navigation bar to display at the bottom of the scaffold.
  ///
978 979
  /// Snack bars slide from underneath the bottom navigation bar while bottom
  /// sheets are stacked on top.
Ian Hickson's avatar
Ian Hickson committed
980 981 982
  ///
  /// The [bottomNavigationBar] is rendered below the [persistentFooterButtons]
  /// and the [body].
983 984
  final Widget bottomNavigationBar;

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  /// The persistent bottom sheet to display.
  ///
  /// A persistent bottom sheet shows information that supplements the primary
  /// content of the app. A persistent bottom sheet remains visible even when
  /// the user interacts with other parts of the app.
  ///
  /// A closely related widget is a modal bottom sheet, which is an alternative
  /// to a menu or a dialog and prevents the user from interacting with the rest
  /// of the app. Modal bottom sheets can be created and displayed with the
  /// [showModalBottomSheet] function.
  ///
  /// Unlike the persistent bottom sheet displayed by [showBottomSheet]
  /// this bottom sheet is not a [LocalHistoryEntry] and cannot be dismissed
  /// with the scaffold appbar's back button.
  ///
  /// If a persistent bottom sheet created with [showBottomSheet] is already
  /// visible, it must be closed before building the Scaffold with a new
  /// [bottomSheet].
  ///
  /// The value of [bottomSheet] can be any widget at all. It's unlikely to
  /// actually be a [BottomSheet], which is used by the implementations of
  /// [showBottomSheet] and [showModalBottomSheet]. Typically it's a widget
  /// that includes [Material].
  ///
  /// See also:
  ///
  ///  * [showBottomSheet], which displays a bottom sheet as a route that can
  ///    be dismissed with the scaffold's back button.
  ///  * [showModalBottomSheet], which displays a modal bottom sheet.
  final Widget bottomSheet;

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  /// This flag is deprecated, please use [resizeToAvoidBottomInset]
  /// instead.
  ///
  /// Originally the name referred [MediaQueryData.padding]. Now it refers
  /// [MediaQueryData.viewInsets], so using [resizeToAvoidBottomInset]
  /// should be clearer to readers.
  @Deprecated('Use resizeToAvoidBottomInset to specify if the body should resize when the keyboard appears')
  final bool resizeToAvoidBottomPadding;

  /// If true the [body] and the scaffold's floating widgets should size
  /// themselves to avoid the onscreen keyboard whose height is defined by the
  /// ambient [MediaQuery]'s [MediaQueryData.viewInsets] `bottom` property.
1028 1029 1030 1031 1032 1033
  ///
  /// For example, if there is an onscreen keyboard displayed above the
  /// scaffold, the body can be resized to avoid overlapping the keyboard, which
  /// prevents widgets inside the body from being obscured by the keyboard.
  ///
  /// Defaults to true.
1034
  final bool resizeToAvoidBottomInset;
1035

1036 1037 1038 1039 1040 1041 1042 1043 1044
  /// Whether this scaffold is being displayed at the top of the screen.
  ///
  /// If true then the height of the [appBar] will be extended by the height
  /// of the screen's status bar, i.e. the top padding for [MediaQuery].
  ///
  /// The default value of this property, like the default value of
  /// [AppBar.primary], is true.
  final bool primary;

1045 1046 1047
  /// {@macro flutter.material.drawer.dragStartBehavior}
  final DragStartBehavior drawerDragStartBehavior;

1048
  /// The state from the closest instance of this class that encloses the given context.
1049
  ///
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  /// {@tool snippet --template=freeform}
  /// Typical usage of the [Scaffold.of] function is to call it from within the
  /// `build` method of a child of a [Scaffold].
  ///
  /// ```dart imports
  /// import 'package:flutter/material.dart';
  /// ```
  ///
  /// ```dart main
  /// void main() => runApp(MyApp());
  /// ```
  ///
  /// ```dart preamble
  /// class MyApp extends StatelessWidget {
  ///   // This widget is the root of your application.
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return MaterialApp(
  ///       title: 'Flutter Code Sample for Scaffold.of.',
  ///       theme: ThemeData(
  ///         primarySwatch: Colors.blue,
  ///       ),
  ///       home: Scaffold(
  ///         body: MyScaffoldBody(),
  ///         appBar: AppBar(title: Text('Scaffold.of Example')),
  ///       ),
  ///       color: Colors.white,
  ///     );
  ///   }
  /// }
  /// ```
1081 1082
  ///
  /// ```dart
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  /// class MyScaffoldBody extends StatelessWidget {
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return Center(
  ///       child: RaisedButton(
  ///         child: Text('SHOW A SNACKBAR'),
  ///         onPressed: () {
  ///           Scaffold.of(context).showSnackBar(
  ///             SnackBar(
  ///               content: Text('Have a snack!'),
  ///             ),
  ///           );
  ///         },
  ///       ),
  ///     );
  ///   }
1099 1100
  /// }
  /// ```
1101
  /// {@end-tool}
1102
  ///
1103
  /// {@tool snippet --template=stateless_widget_material}
1104 1105
  /// When the [Scaffold] is actually created in the same `build` function, the
  /// `context` argument to the `build` function can't be used to find the
1106 1107 1108 1109
  /// [Scaffold] (since it's "above" the widget being returned in the widget
  /// tree). In such cases, the following technique with a [Builder] can be used
  /// to provide a new scope with a [BuildContext] that is "under" the
  /// [Scaffold]:
1110 1111 1112
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
1113 1114 1115
  ///   return Scaffold(
  ///     appBar: AppBar(
  ///       title: Text('Demo')
1116
  ///     ),
1117
  ///     body: Builder(
1118 1119 1120
  ///       // Create an inner BuildContext so that the onPressed methods
  ///       // can refer to the Scaffold with Scaffold.of().
  ///       builder: (BuildContext context) {
1121 1122 1123
  ///         return Center(
  ///           child: RaisedButton(
  ///             child: Text('SHOW A SNACKBAR'),
1124
  ///             onPressed: () {
1125
  ///               Scaffold.of(context).showSnackBar(SnackBar(
1126
  ///                 content: Text('Have a snack!'),
1127 1128 1129 1130 1131 1132 1133 1134 1135
  ///               ));
  ///             },
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
1136
  /// {@end-tool}
1137
  ///
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  /// A more efficient solution is to split your build function into several
  /// widgets. This introduces a new context from which you can obtain the
  /// [Scaffold]. In this solution, you would have an outer widget that creates
  /// the [Scaffold] populated by instances of your new inner widgets, and then
  /// in these inner widgets you would use [Scaffold.of].
  ///
  /// A less elegant but more expedient solution is assign a [GlobalKey] to the
  /// [Scaffold], then use the `key.currentState` property to obtain the
  /// [ScaffoldState] rather than using the [Scaffold.of] function.
  ///
1148 1149
  /// If there is no [Scaffold] in scope, then this will throw an exception.
  /// To return null if there is no [Scaffold], then pass `nullOk: true`.
1150
  static ScaffoldState of(BuildContext context, { bool nullOk = false }) {
1151 1152
    assert(nullOk != null);
    assert(context != null);
1153
    final ScaffoldState result = context.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
1154 1155
    if (nullOk || result != null)
      return result;
1156
    throw FlutterError(
1157
      'Scaffold.of() called with a context that does not contain a Scaffold.\n'
1158
      'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). '
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
      'This usually happens when the context provided is from the same StatefulWidget as that '
      'whose build function actually creates the Scaffold widget being sought.\n'
      'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
      'context that is "under" the Scaffold. For an example of this, please see the '
      'documentation for Scaffold.of():\n'
      '  https://docs.flutter.io/flutter/material/Scaffold/of.html\n'
      'A more efficient solution is to split your build function into several widgets. This '
      'introduces a new context from which you can obtain the Scaffold. In this solution, '
      'you would have an outer widget that creates the Scaffold populated by instances of '
      'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n'
      'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, '
      'then use the key.currentState property to obtain the ScaffoldState rather than '
      'using the Scaffold.of() function.\n'
      'The context used was:\n'
      '  $context'
    );
  }
Hixie's avatar
Hixie committed
1176

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  /// Returns a [ValueListenable] for the [ScaffoldGeometry] for the closest
  /// [Scaffold] ancestor of the given context.
  ///
  /// The [ValueListenable.value] is only available at paint time.
  ///
  /// Notifications are guaranteed to be sent before the first paint pass
  /// with the new geometry, but there is no guarantee whether a build or
  /// layout passes are going to happen between the notification and the next
  /// paint pass.
  ///
  /// The closest [Scaffold] ancestor for the context might change, e.g when
  /// an element is moved from one scaffold to another. For [StatefulWidget]s
  /// using this listenable, a change of the [Scaffold] ancestor will
  /// trigger a [State.didChangeDependencies].
  ///
  /// A typical pattern for listening to the scaffold geometry would be to
  /// call [Scaffold.geometryOf] in [State.didChangeDependencies], compare the
  /// return value with the previous listenable, if it has changed, unregister
  /// the listener, and register a listener to the new [ScaffoldGeometry]
  /// listenable.
  static ValueListenable<ScaffoldGeometry> geometryOf(BuildContext context) {
    final _ScaffoldScope scaffoldScope = context.inheritFromWidgetOfExactType(_ScaffoldScope);
    if (scaffoldScope == null)
1200
      throw FlutterError(
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        'Scaffold.geometryOf() called with a context that does not contain a Scaffold.\n'
        'This usually happens when the context provided is from the same StatefulWidget as that '
        'whose build function actually creates the Scaffold widget being sought.\n'
        'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
        'context that is "under" the Scaffold. For an example of this, please see the '
        'documentation for Scaffold.of():\n'
        '  https://docs.flutter.io/flutter/material/Scaffold/of.html\n'
        'A more efficient solution is to split your build function into several widgets. This '
        'introduces a new context from which you can obtain the Scaffold. In this solution, '
        'you would have an outer widget that creates the Scaffold populated by instances of '
        'your new inner widgets, and then in these inner widgets you would use Scaffold.geometryOf().\n'
        'The context used was:\n'
        '  $context'
      );

    return scaffoldScope.geometryNotifier;
  }

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  /// Whether the Scaffold that most tightly encloses the given context has a
  /// drawer.
  ///
  /// If this is being used during a build (for example to decide whether to
  /// show an "open drawer" button), set the `registerForUpdates` argument to
  /// true. This will then set up an [InheritedWidget] relationship with the
  /// [Scaffold] so that the client widget gets rebuilt whenever the [hasDrawer]
  /// value changes.
  ///
  /// See also:
1229
  ///
1230 1231
  ///  * [Scaffold.of], which provides access to the [ScaffoldState] object as a
  ///    whole, from which you can show snackbars, bottom sheets, and so forth.
1232
  static bool hasDrawer(BuildContext context, { bool registerForUpdates = true }) {
1233 1234 1235
    assert(registerForUpdates != null);
    assert(context != null);
    if (registerForUpdates) {
1236
      final _ScaffoldScope scaffold = context.inheritFromWidgetOfExactType(_ScaffoldScope);
1237 1238
      return scaffold?.hasDrawer ?? false;
    } else {
1239
      final ScaffoldState scaffold = context.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
1240 1241 1242 1243
      return scaffold?.hasDrawer ?? false;
    }
  }

1244
  @override
1245
  ScaffoldState createState() => ScaffoldState();
Hixie's avatar
Hixie committed
1246 1247
}

1248 1249 1250 1251
/// State for a [Scaffold].
///
/// Can display [SnackBar]s and [BottomSheet]s. Retrieve a [ScaffoldState] from
/// the current [BuildContext] using [Scaffold.of].
1252
class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
Hixie's avatar
Hixie committed
1253

1254 1255
  // DRAWER API

1256 1257
  final GlobalKey<DrawerControllerState> _drawerKey = GlobalKey<DrawerControllerState>();
  final GlobalKey<DrawerControllerState> _endDrawerKey = GlobalKey<DrawerControllerState>();
1258

1259
  /// Whether this scaffold has a non-null [Scaffold.drawer].
1260
  bool get hasDrawer => widget.drawer != null;
1261 1262
  /// Whether this scaffold has a non-null [Scaffold.endDrawer].
  bool get hasEndDrawer => widget.endDrawer != null;
1263

jslavitz's avatar
jslavitz committed
1264 1265 1266
  bool _drawerOpened = false;
  bool _endDrawerOpened = false;

1267 1268 1269 1270
  /// Whether the [Scaffold.drawer] is opened.
  ///
  /// See also:
  ///
1271 1272
  ///  * [ScaffoldState.openDrawer], which opens the [Scaffold.drawer] of a
  ///    [Scaffold].
1273 1274 1275 1276 1277 1278
  bool get isDrawerOpen => _drawerOpened;

  /// Whether the [Scaffold.endDrawer] is opened.
  ///
  /// See also:
  ///
1279 1280
  ///  * [ScaffoldState.openEndDrawer], which opens the [Scaffold.endDrawer] of
  ///    a [Scaffold].
1281 1282
  bool get isEndDrawerOpen => _endDrawerOpened;

jslavitz's avatar
jslavitz committed
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  void _drawerOpenedCallback(bool isOpened) {
    setState(() {
      _drawerOpened = isOpened;
    });
  }

  void _endDrawerOpenedCallback(bool isOpened) {
    setState(() {
      _endDrawerOpened = isOpened;
    });
  }

1295 1296 1297 1298
  /// Opens the [Drawer] (if any).
  ///
  /// If the scaffold has a non-null [Scaffold.drawer], this function will cause
  /// the drawer to begin its entrance animation.
1299 1300 1301 1302 1303 1304
  ///
  /// Normally this is not needed since the [Scaffold] automatically shows an
  /// appropriate [IconButton], and handles the edge-swipe gesture, to show the
  /// drawer.
  ///
  /// To close the drawer once it is open, use [Navigator.pop].
1305 1306
  ///
  /// See [Scaffold.of] for information about how to obtain the [ScaffoldState].
1307
  void openDrawer() {
jslavitz's avatar
jslavitz committed
1308 1309
    if (_endDrawerKey.currentState != null && _endDrawerOpened)
      _endDrawerKey.currentState.close();
1310
    _drawerKey.currentState?.open();
1311 1312
  }

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
  /// Opens the end side [Drawer] (if any).
  ///
  /// If the scaffold has a non-null [Scaffold.endDrawer], this function will cause
  /// the end side drawer to begin its entrance animation.
  ///
  /// Normally this is not needed since the [Scaffold] automatically shows an
  /// appropriate [IconButton], and handles the edge-swipe gesture, to show the
  /// drawer.
  ///
  /// To close the end side drawer once it is open, use [Navigator.pop].
  ///
  /// See [Scaffold.of] for information about how to obtain the [ScaffoldState].
  void openEndDrawer() {
jslavitz's avatar
jslavitz committed
1326 1327
    if (_drawerKey.currentState != null && _drawerOpened)
      _drawerKey.currentState.close();
1328 1329 1330
    _endDrawerKey.currentState?.open();
  }

1331 1332
  // SNACKBAR API

1333
  final Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>> _snackBars = Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>();
1334
  AnimationController _snackBarController;
Hixie's avatar
Hixie committed
1335
  Timer _snackBarTimer;
1336
  bool _accessibleNavigation;
Hixie's avatar
Hixie committed
1337

1338
  /// Shows a [SnackBar] at the bottom of the scaffold.
1339 1340 1341 1342 1343
  ///
  /// A scaffold can show at most one snack bar at a time. If this function is
  /// called while another snack bar is already visible, the given snack bar
  /// will be added to a queue and displayed after the earlier snack bars have
  /// closed.
1344 1345 1346
  ///
  /// To control how long a [SnackBar] remains visible, use [SnackBar.duration].
  ///
1347 1348 1349 1350
  /// To remove the [SnackBar] with an exit animation, use [hideCurrentSnackBar]
  /// or call [ScaffoldFeatureController.close] on the returned
  /// [ScaffoldFeatureController]. To remove a [SnackBar] suddenly (without an
  /// animation), use [removeCurrentSnackBar].
1351 1352
  ///
  /// See [Scaffold.of] for information about how to obtain the [ScaffoldState].
1353
  ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(SnackBar snackbar) {
1354
    _snackBarController ??= SnackBar.createAnimationController(vsync: this)
Hixie's avatar
Hixie committed
1355
      ..addStatusListener(_handleSnackBarStatusChange);
1356
    if (_snackBars.isEmpty) {
1357 1358
      assert(_snackBarController.isDismissed);
      _snackBarController.forward();
1359
    }
1360
    ScaffoldFeatureController<SnackBar, SnackBarClosedReason> controller;
1361
    controller = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>._(
1362 1363 1364
      // We provide a fallback key so that if back-to-back snackbars happen to
      // match in structure, material ink splashes and highlights don't survive
      // from one to the next.
1365 1366
      snackbar.withAnimation(_snackBarController, fallbackKey: UniqueKey()),
      Completer<SnackBarClosedReason>(),
1367 1368
      () {
        assert(_snackBars.first == controller);
1369
        hideCurrentSnackBar(reason: SnackBarClosedReason.hide);
1370
      },
1371
      null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
1372
    );
Hixie's avatar
Hixie committed
1373
    setState(() {
1374
      _snackBars.addLast(controller);
Hixie's avatar
Hixie committed
1375
    });
1376
    return controller;
Hixie's avatar
Hixie committed
1377 1378
  }

1379
  void _handleSnackBarStatusChange(AnimationStatus status) {
Hixie's avatar
Hixie committed
1380
    switch (status) {
1381
      case AnimationStatus.dismissed:
Hixie's avatar
Hixie committed
1382 1383 1384 1385
        assert(_snackBars.isNotEmpty);
        setState(() {
          _snackBars.removeFirst();
        });
1386
        if (_snackBars.isNotEmpty)
1387
          _snackBarController.forward();
Hixie's avatar
Hixie committed
1388
        break;
1389
      case AnimationStatus.completed:
Hixie's avatar
Hixie committed
1390 1391 1392 1393 1394
        setState(() {
          assert(_snackBarTimer == null);
          // build will create a new timer if necessary to dismiss the snack bar
        });
        break;
1395 1396
      case AnimationStatus.forward:
      case AnimationStatus.reverse:
Hixie's avatar
Hixie committed
1397 1398 1399 1400
        break;
    }
  }

1401 1402 1403 1404
  /// Removes the current [SnackBar] (if any) immediately.
  ///
  /// The removed snack bar does not run its normal exit animation. If there are
  /// any queued snack bars, they begin their entrance animation immediately.
1405
  void removeCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.remove }) {
1406
    assert(reason != null);
1407 1408
    if (_snackBars.isEmpty)
      return;
1409
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
1410
    if (!completer.isCompleted)
1411
      completer.complete(reason);
1412 1413 1414 1415 1416
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
    _snackBarController.value = 0.0;
  }

1417
  /// Removes the current [SnackBar] by running its normal exit animation.
1418 1419
  ///
  /// The closed completer is called after the animation is complete.
1420
  void hideCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.hide }) {
1421 1422 1423
    assert(reason != null);
    if (_snackBars.isEmpty || _snackBarController.status == AnimationStatus.dismissed)
      return;
1424
    final MediaQueryData mediaQuery = MediaQuery.of(context);
1425
    final Completer<SnackBarClosedReason> completer = _snackBars.first._completer;
1426 1427 1428 1429
    if (mediaQuery.accessibleNavigation) {
      _snackBarController.value = 0.0;
      completer.complete(reason);
    } else {
1430
      _snackBarController.reverse().then<void>((void value) {
1431 1432 1433 1434 1435
        assert(mounted);
        if (!completer.isCompleted)
          completer.complete(reason);
      });
    }
1436
    _snackBarTimer?.cancel();
Hixie's avatar
Hixie committed
1437 1438 1439
    _snackBarTimer = null;
  }

1440

1441 1442
  // PERSISTENT BOTTOM SHEET API

1443
  final List<_PersistentBottomSheet> _dismissedBottomSheets = <_PersistentBottomSheet>[];
1444
  PersistentBottomSheetController<dynamic> _currentBottomSheet;
1445

1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
  void _maybeBuildCurrentBottomSheet() {
    if (widget.bottomSheet != null) {
      // The new _currentBottomSheet is not a local history entry so a "back" button
      // will not be added to the Scaffold's appbar and the bottom sheet will not
      // support drag or swipe to dismiss.
      _currentBottomSheet = _buildBottomSheet<void>(
        (BuildContext context) => widget.bottomSheet,
        BottomSheet.createAnimationController(this) ..value = 1.0,
        false,
      );
    }
  }

  void _closeCurrentBottomSheet() {
1460 1461 1462 1463
    if (_currentBottomSheet != null) {
      _currentBottomSheet.close();
      assert(_currentBottomSheet == null);
    }
1464 1465 1466
  }

  PersistentBottomSheetController<T> _buildBottomSheet<T>(WidgetBuilder builder, AnimationController controller, bool isLocalHistoryEntry) {
1467 1468
    final Completer<T> completer = Completer<T>();
    final GlobalKey<_PersistentBottomSheetState> bottomSheetKey = GlobalKey<_PersistentBottomSheetState>();
1469
    _PersistentBottomSheet bottomSheet;
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

    void _removeCurrentBottomSheet() {
      assert(_currentBottomSheet._widget == bottomSheet);
      assert(bottomSheetKey.currentState != null);
      bottomSheetKey.currentState.close();
      if (controller.status != AnimationStatus.dismissed)
        _dismissedBottomSheets.add(bottomSheet);
      setState(() {
        _currentBottomSheet = null;
      });
      completer.complete();
    }

    final LocalHistoryEntry entry = isLocalHistoryEntry
1484
      ? LocalHistoryEntry(onRemove: _removeCurrentBottomSheet)
1485 1486
      : null;

1487
    bottomSheet = _PersistentBottomSheet(
1488
      key: bottomSheetKey,
1489
      animationController: controller,
1490
      enableDrag: isLocalHistoryEntry,
1491 1492
      onClosing: () {
        assert(_currentBottomSheet._widget == bottomSheet);
1493 1494 1495 1496
        if (isLocalHistoryEntry)
          entry.remove();
        else
          _removeCurrentBottomSheet();
1497 1498
      },
      onDismissed: () {
1499
        if (_dismissedBottomSheets.contains(bottomSheet)) {
1500
          bottomSheet.animationController.dispose();
1501 1502 1503 1504
          setState(() {
            _dismissedBottomSheets.remove(bottomSheet);
          });
        }
1505
      },
1506
      builder: builder,
1507
    );
1508 1509 1510 1511

    if (isLocalHistoryEntry)
      ModalRoute.of(context).addLocalHistoryEntry(entry);

1512
    return PersistentBottomSheetController<T>._(
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
      bottomSheet,
      completer,
      isLocalHistoryEntry ? entry.remove : _removeCurrentBottomSheet,
      (VoidCallback fn) { bottomSheetKey.currentState?.setState(fn); },
      isLocalHistoryEntry,
    );
  }

  /// Shows a persistent material design bottom sheet in the nearest [Scaffold].
  ///
  /// Returns a controller that can be used to close and otherwise manipulate the
  /// bottom sheet.
  ///
  /// To rebuild the bottom sheet (e.g. if it is stateful), call
  /// [PersistentBottomSheetController.setState] on the controller returned by
  /// this method.
  ///
  /// The new bottom sheet becomes a [LocalHistoryEntry] for the enclosing
  /// [ModalRoute] and a back button is added to the appbar of the [Scaffold]
  /// that closes the bottom sheet.
  ///
  /// To create a persistent bottom sheet that is not a [LocalHistoryEntry] and
  /// does not add a back button to the enclosing Scaffold's appbar, use the
  /// [Scaffold.bottomSheet] constructor parameter.
  ///
  /// A persistent bottom sheet shows information that supplements the primary
  /// content of the app. A persistent bottom sheet remains visible even when
  /// the user interacts with other parts of the app.
  ///
  /// A closely related widget is a modal bottom sheet, which is an alternative
  /// to a menu or a dialog and prevents the user from interacting with the rest
  /// of the app. Modal bottom sheets can be created and displayed with the
  /// [showModalBottomSheet] function.
  ///
  /// See also:
  ///
  ///  * [BottomSheet], which is the widget typically returned by the `builder`.
  ///  * [showBottomSheet], which calls this method given a [BuildContext].
  ///  * [showModalBottomSheet], which can be used to display a modal bottom
  ///    sheet.
  ///  * [Scaffold.of], for information about how to obtain the [ScaffoldState].
1554
  ///  * <https://material.io/design/components/sheets-bottom.html#standard-bottom-sheet>
1555 1556 1557 1558
  PersistentBottomSheetController<T> showBottomSheet<T>(WidgetBuilder builder) {
    _closeCurrentBottomSheet();
    final AnimationController controller = BottomSheet.createAnimationController(this)
      ..forward();
1559
    setState(() {
1560
      _currentBottomSheet = _buildBottomSheet<T>(builder, controller, true);
1561 1562 1563 1564
    });
    return _currentBottomSheet;
  }

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  // Floating Action Button API
  AnimationController _floatingActionButtonMoveController;
  FloatingActionButtonAnimator _floatingActionButtonAnimator;
  FloatingActionButtonLocation _previousFloatingActionButtonLocation;
  FloatingActionButtonLocation _floatingActionButtonLocation;

  // Moves the Floating Action Button to the new Floating Action Button Location.
  void _moveFloatingActionButton(final FloatingActionButtonLocation newLocation) {
    FloatingActionButtonLocation previousLocation = _floatingActionButtonLocation;
    double restartAnimationFrom = 0.0;
    // If the Floating Action Button is moving right now, we need to start from a snapshot of the current transition.
    if (_floatingActionButtonMoveController.isAnimating) {
1577
      previousLocation = _TransitionSnapshotFabLocation(_previousFloatingActionButtonLocation, _floatingActionButtonLocation, _floatingActionButtonAnimator, _floatingActionButtonMoveController.value);
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
      restartAnimationFrom = _floatingActionButtonAnimator.getAnimationRestart(_floatingActionButtonMoveController.value);
    }

    setState(() {
      _previousFloatingActionButtonLocation = previousLocation;
      _floatingActionButtonLocation = newLocation;
    });

    // Animate the motion even when the fab is null so that if the exit animation is running,
    // the old fab will start the motion transition while it exits instead of jumping to the
    // new position.
    _floatingActionButtonMoveController.forward(from: restartAnimationFrom);
  }
1591

1592
  // iOS FEATURES - status bar tap, back gesture
1593

1594 1595 1596
  // On iOS, tapping the status bar scrolls the app's primary scrollable to the
  // top. We implement this by providing a primary scroll controller and
  // scrolling it to the top when tapped.
1597

1598
  final ScrollController _primaryScrollController = ScrollController();
Hixie's avatar
Hixie committed
1599

1600 1601 1602 1603 1604 1605
  void _handleStatusBarTap() {
    if (_primaryScrollController.hasClients) {
      _primaryScrollController.animateTo(
        0.0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.linear, // TODO(ianh): Use a more appropriate curve.
1606 1607 1608 1609
      );
    }
  }

1610 1611
  // INTERNALS

1612 1613
  _ScaffoldGeometryNotifier _geometryNotifier;

1614 1615
  // Backwards compatibility for deprecated resizeToAvoidBottomPadding property
  bool get _resizeToAvoidBottomInset {
1616
    // ignore: deprecated_member_use_from_same_package
1617 1618 1619
    return widget.resizeToAvoidBottomInset ?? widget.resizeToAvoidBottomPadding ?? true;
  }

1620 1621 1622
  @override
  void initState() {
    super.initState();
1623
    _geometryNotifier = _ScaffoldGeometryNotifier(const ScaffoldGeometry(), context);
1624 1625 1626
    _floatingActionButtonLocation = widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation;
    _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator;
    _previousFloatingActionButtonLocation = _floatingActionButtonLocation;
1627
    _floatingActionButtonMoveController = AnimationController(
1628 1629 1630 1631
      vsync: this,
      lowerBound: 0.0,
      upperBound: 1.0,
      value: 1.0,
1632 1633
      duration: kFloatingActionButtonSegue * 2,
    );
1634
    _maybeBuildCurrentBottomSheet();
1635 1636
  }

1637 1638 1639 1640 1641 1642 1643 1644 1645
  @override
  void didUpdateWidget(Scaffold oldWidget) {
    // Update the Floating Action Button Animator, and then schedule the Floating Action Button for repositioning.
    if (widget.floatingActionButtonAnimator != oldWidget.floatingActionButtonAnimator) {
      _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator;
    }
    if (widget.floatingActionButtonLocation != oldWidget.floatingActionButtonLocation) {
      _moveFloatingActionButton(widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation);
    }
1646 1647 1648
    if (widget.bottomSheet != oldWidget.bottomSheet) {
      assert(() {
        if (widget.bottomSheet != null && _currentBottomSheet?._isLocalHistoryEntry == true) {
1649
          throw FlutterError(
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
            'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed '
            'with showBottomSheet() is still visible.\n Use the PersistentBottomSheetController '
            'returned by showBottomSheet() to close the old bottom sheet before creating '
            'a Scaffold with a (non null) bottomSheet.'
          );
        }
        return true;
      }());
      _closeCurrentBottomSheet();
      _maybeBuildCurrentBottomSheet();
    }
1661 1662 1663
    super.didUpdateWidget(oldWidget);
  }

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
  @override
  void didChangeDependencies() {
    final MediaQueryData mediaQuery = MediaQuery.of(context);
    // If we transition from accessible navigation to non-accessible navigation
    // and there is a SnackBar that would have timed out that has already
    // completed its timer, dismiss that SnackBar. If the timer hasn't finished
    // yet, let it timeout as normal.
    if (_accessibleNavigation == true
      && !mediaQuery.accessibleNavigation
      && _snackBarTimer != null
      && !_snackBarTimer.isActive) {
      hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
    }
    _accessibleNavigation = mediaQuery.accessibleNavigation;
    super.didChangeDependencies();
  }

1681 1682 1683 1684 1685
  @override
  void dispose() {
    _snackBarController?.dispose();
    _snackBarTimer?.cancel();
    _snackBarTimer = null;
1686
    _geometryNotifier.dispose();
1687 1688 1689 1690
    for (_PersistentBottomSheet bottomSheet in _dismissedBottomSheets)
      bottomSheet.animationController.dispose();
    if (_currentBottomSheet != null)
      _currentBottomSheet._widget.animationController.dispose();
1691
    _floatingActionButtonMoveController.dispose();
1692 1693 1694
    super.dispose();
  }

1695 1696 1697 1698
  void _addIfNonNull(
    List<LayoutId> children,
    Widget child,
    Object childId, {
Ian Hickson's avatar
Ian Hickson committed
1699 1700 1701
    @required bool removeLeftPadding,
    @required bool removeTopPadding,
    @required bool removeRightPadding,
1702
    @required bool removeBottomPadding,
1703
    bool removeBottomInset = false,
Ian Hickson's avatar
Ian Hickson committed
1704
  }) {
1705 1706 1707 1708 1709 1710 1711 1712 1713
    MediaQueryData data = MediaQuery.of(context).removePadding(
      removeLeft: removeLeftPadding,
      removeTop: removeTopPadding,
      removeRight: removeRightPadding,
      removeBottom: removeBottomPadding,
    );
    if (removeBottomInset)
      data = data.removeViewInsets(removeBottom: true);

Ian Hickson's avatar
Ian Hickson committed
1714 1715
    if (child != null) {
      children.add(
1716
        LayoutId(
Ian Hickson's avatar
Ian Hickson committed
1717
          id: childId,
1718
          child: MediaQuery(data: data, child: child),
Ian Hickson's avatar
Ian Hickson committed
1719 1720 1721
        ),
      );
    }
1722 1723
  }

jslavitz's avatar
jslavitz committed
1724 1725 1726 1727 1728
  void _buildEndDrawer(List<LayoutId> children, TextDirection textDirection) {
    if (widget.endDrawer != null) {
      assert(hasEndDrawer);
      _addIfNonNull(
        children,
1729
        DrawerController(
jslavitz's avatar
jslavitz committed
1730 1731 1732 1733
          key: _endDrawerKey,
          alignment: DrawerAlignment.end,
          child: widget.endDrawer,
          drawerCallback: _endDrawerOpenedCallback,
1734
          dragStartBehavior: widget.drawerDragStartBehavior,
jslavitz's avatar
jslavitz committed
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
        ),
        _ScaffoldSlot.endDrawer,
        // remove the side padding from the side we're not touching
        removeLeftPadding: textDirection == TextDirection.ltr,
        removeTopPadding: false,
        removeRightPadding: textDirection == TextDirection.rtl,
        removeBottomPadding: false,
      );
    }
  }

  void _buildDrawer(List<LayoutId> children, TextDirection textDirection) {
    if (widget.drawer != null) {
      assert(hasDrawer);
      _addIfNonNull(
        children,
1751
        DrawerController(
jslavitz's avatar
jslavitz committed
1752 1753 1754 1755
          key: _drawerKey,
          alignment: DrawerAlignment.start,
          child: widget.drawer,
          drawerCallback: _drawerOpenedCallback,
1756
          dragStartBehavior: widget.drawerDragStartBehavior,
jslavitz's avatar
jslavitz committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        ),
        _ScaffoldSlot.drawer,
        // remove the side padding from the side we're not touching
        removeLeftPadding: textDirection == TextDirection.rtl,
        removeTopPadding: false,
        removeRightPadding: textDirection == TextDirection.ltr,
        removeBottomPadding: false,
      );
    }
  }

1768
  @override
Adam Barth's avatar
Adam Barth committed
1769
  Widget build(BuildContext context) {
1770
    assert(debugCheckHasMediaQuery(context));
Ian Hickson's avatar
Ian Hickson committed
1771
    assert(debugCheckHasDirectionality(context));
1772
    final MediaQueryData mediaQuery = MediaQuery.of(context);
1773
    final ThemeData themeData = Theme.of(context);
Ian Hickson's avatar
Ian Hickson committed
1774
    final TextDirection textDirection = Directionality.of(context);
1775
    _accessibleNavigation = mediaQuery.accessibleNavigation;
Hixie's avatar
Hixie committed
1776

1777
    if (_snackBars.isNotEmpty) {
1778
      final ModalRoute<dynamic> route = ModalRoute.of(context);
Hixie's avatar
Hixie committed
1779
      if (route == null || route.isCurrent) {
1780 1781
        if (_snackBarController.isCompleted && _snackBarTimer == null) {
          final SnackBar snackBar = _snackBars.first._widget;
1782
          _snackBarTimer = Timer(snackBar.duration, () {
1783
            assert(_snackBarController.status == AnimationStatus.forward ||
1784 1785 1786 1787 1788
                   _snackBarController.status == AnimationStatus.completed);
            // Look up MediaQuery again in case the setting changed.
            final MediaQueryData mediaQuery = MediaQuery.of(context);
            if (mediaQuery.accessibleNavigation && snackBar.action != null)
              return;
1789 1790
            hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
          });
1791
        }
Hixie's avatar
Hixie committed
1792 1793 1794 1795
      } else {
        _snackBarTimer?.cancel();
        _snackBarTimer = null;
      }
1796
    }
1797

1798
    final List<LayoutId> children = <LayoutId>[];
1799

Ian Hickson's avatar
Ian Hickson committed
1800 1801
    _addIfNonNull(
      children,
1802
      widget.body != null && widget.extendBody ? _BodyBuilder(body: widget.body) : widget.body,
Ian Hickson's avatar
Ian Hickson committed
1803 1804 1805 1806
      _ScaffoldSlot.body,
      removeLeftPadding: false,
      removeTopPadding: widget.appBar != null,
      removeRightPadding: false,
1807 1808
      removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
      removeBottomInset: _resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
1809
    );
1810

1811
    if (widget.appBar != null) {
1812
      final double topPadding = widget.primary ? mediaQuery.padding.top : 0.0;
1813 1814
      final double extent = widget.appBar.preferredSize.height + topPadding;
      assert(extent >= 0.0 && extent.isFinite);
1815 1816
      _addIfNonNull(
        children,
1817 1818
        ConstrainedBox(
          constraints: BoxConstraints(maxHeight: extent),
1819 1820 1821 1822
          child: FlexibleSpaceBar.createSettings(
            currentExtent: extent,
            child: widget.appBar,
          ),
1823 1824
        ),
        _ScaffoldSlot.appBar,
Ian Hickson's avatar
Ian Hickson committed
1825 1826 1827 1828
        removeLeftPadding: false,
        removeTopPadding: false,
        removeRightPadding: false,
        removeBottomPadding: true,
1829 1830
      );
    }
1831

Ian Hickson's avatar
Ian Hickson committed
1832 1833 1834 1835 1836 1837 1838 1839
    if (_snackBars.isNotEmpty) {
      _addIfNonNull(
        children,
        _snackBars.first._widget,
        _ScaffoldSlot.snackBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
1840
        removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null,
Ian Hickson's avatar
Ian Hickson committed
1841 1842
      );
    }
1843

1844
    if (widget.persistentFooterButtons != null) {
Ian Hickson's avatar
Ian Hickson committed
1845 1846
      _addIfNonNull(
        children,
1847 1848 1849
        Container(
          decoration: BoxDecoration(
            border: Border(
1850
              top: Divider.createBorderSide(context, width: 1.0),
1851 1852
            ),
          ),
1853 1854 1855
          child: SafeArea(
            child: ButtonTheme.bar(
              child: SafeArea(
1856
                top: false,
1857
                child: ButtonBar(
1858
                  children: widget.persistentFooterButtons,
1859
                ),
Ian Hickson's avatar
Ian Hickson committed
1860
              ),
1861 1862 1863
            ),
          ),
        ),
Ian Hickson's avatar
Ian Hickson committed
1864 1865 1866 1867
        _ScaffoldSlot.persistentFooter,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
1868
        removeBottomPadding: false,
Ian Hickson's avatar
Ian Hickson committed
1869
      );
1870 1871
    }

1872
    if (widget.bottomNavigationBar != null) {
Ian Hickson's avatar
Ian Hickson committed
1873 1874 1875 1876 1877 1878 1879
      _addIfNonNull(
        children,
        widget.bottomNavigationBar,
        _ScaffoldSlot.bottomNavigationBar,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
1880
        removeBottomPadding: false,
Ian Hickson's avatar
Ian Hickson committed
1881
      );
1882
    }
1883

1884
    if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) {
1885
      final List<Widget> bottomSheets = <Widget>[];
1886
      if (_dismissedBottomSheets.isNotEmpty)
1887 1888 1889
        bottomSheets.addAll(_dismissedBottomSheets);
      if (_currentBottomSheet != null)
        bottomSheets.add(_currentBottomSheet._widget);
1890
      final Widget stack = Stack(
1891
        children: bottomSheets,
1892
        alignment: Alignment.bottomCenter,
1893
      );
Ian Hickson's avatar
Ian Hickson committed
1894 1895 1896 1897 1898 1899 1900
      _addIfNonNull(
        children,
        stack,
        _ScaffoldSlot.bottomSheet,
        removeLeftPadding: false,
        removeTopPadding: true,
        removeRightPadding: false,
1901
        removeBottomPadding: _resizeToAvoidBottomInset,
Ian Hickson's avatar
Ian Hickson committed
1902
      );
1903 1904
    }

Ian Hickson's avatar
Ian Hickson committed
1905 1906
    _addIfNonNull(
      children,
1907
      _FloatingActionButtonTransition(
1908
        child: widget.floatingActionButton,
1909 1910
        fabMoveAnimation: _floatingActionButtonMoveController,
        fabMotionAnimator: _floatingActionButtonAnimator,
1911
        geometryNotifier: _geometryNotifier,
Ian Hickson's avatar
Ian Hickson committed
1912 1913 1914 1915 1916 1917 1918
      ),
      _ScaffoldSlot.floatingActionButton,
      removeLeftPadding: true,
      removeTopPadding: true,
      removeRightPadding: true,
      removeBottomPadding: true,
    );
1919

1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
    switch (themeData.platform) {
      case TargetPlatform.iOS:
        _addIfNonNull(
          children,
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: _handleStatusBarTap,
            // iOS accessibility automatically adds scroll-to-top to the clock in the status bar
            excludeFromSemantics: true,
          ),
          _ScaffoldSlot.statusBar,
          removeLeftPadding: false,
          removeTopPadding: true,
          removeRightPadding: false,
          removeBottomPadding: true,
        );
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        break;
1940 1941
    }

jslavitz's avatar
jslavitz committed
1942 1943 1944 1945 1946 1947
    if (_endDrawerOpened) {
      _buildDrawer(children, textDirection);
      _buildEndDrawer(children, textDirection);
    } else {
      _buildEndDrawer(children, textDirection);
      _buildDrawer(children, textDirection);
1948 1949
    }

1950 1951
    // The minimum insets for contents of the Scaffold to keep visible.
    final EdgeInsets minInsets = mediaQuery.padding.copyWith(
1952
      bottom: _resizeToAvoidBottomInset ? mediaQuery.viewInsets.bottom : 0.0,
1953
    );
1954

1955 1956 1957
    // extendBody locked when keyboard is open
    final bool _extendBody = minInsets.bottom > 0 ? false : widget.extendBody;

1958
    return _ScaffoldScope(
1959
      hasDrawer: hasDrawer,
1960
      geometryNotifier: _geometryNotifier,
1961
      child: PrimaryScrollController(
1962
        controller: _primaryScrollController,
1963
        child: Material(
1964
          color: widget.backgroundColor ?? themeData.scaffoldBackgroundColor,
1965 1966
          child: AnimatedBuilder(animation: _floatingActionButtonMoveController, builder: (BuildContext context, Widget child) {
            return CustomMultiChildLayout(
1967
              children: children,
1968
              delegate: _ScaffoldLayout(
1969
                extendBody: _extendBody,
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
                minInsets: minInsets,
                currentFloatingActionButtonLocation: _floatingActionButtonLocation,
                floatingActionButtonMoveAnimationProgress: _floatingActionButtonMoveController.value,
                floatingActionButtonMotionAnimator: _floatingActionButtonAnimator,
                geometryNotifier: _geometryNotifier,
                previousFloatingActionButtonLocation: _previousFloatingActionButtonLocation,
                textDirection: textDirection,
              ),
            );
          }),
1980 1981
        ),
      ),
1982
    );
1983
  }
1984
}
1985

1986 1987
/// An interface for controlling a feature of a [Scaffold].
///
1988
/// Commonly obtained from [ScaffoldState.showSnackBar] or [ScaffoldState.showBottomSheet].
1989
class ScaffoldFeatureController<T extends Widget, U> {
1990 1991
  const ScaffoldFeatureController._(this._widget, this._completer, this.close, this.setState);
  final T _widget;
1992
  final Completer<U> _completer;
1993 1994

  /// Completes when the feature controlled by this object is no longer visible.
1995
  Future<U> get closed => _completer.future;
1996 1997 1998 1999 2000

  /// Remove the feature (e.g., bottom sheet or snack bar) from the scaffold.
  final VoidCallback close;

  /// Mark the feature (e.g., bottom sheet or snack bar) as needing to rebuild.
2001 2002 2003
  final StateSetter setState;
}

2004
class _PersistentBottomSheet extends StatefulWidget {
2005
  const _PersistentBottomSheet({
2006
    Key key,
2007
    this.animationController,
2008
    this.enableDrag = true,
2009 2010
    this.onClosing,
    this.onDismissed,
2011
    this.builder,
2012 2013
  }) : super(key: key);

2014
  final AnimationController animationController; // we control it, but it must be disposed by whoever created it
2015
  final bool enableDrag;
2016 2017 2018 2019
  final VoidCallback onClosing;
  final VoidCallback onDismissed;
  final WidgetBuilder builder;

2020
  @override
2021
  _PersistentBottomSheetState createState() => _PersistentBottomSheetState();
2022 2023 2024
}

class _PersistentBottomSheetState extends State<_PersistentBottomSheet> {
2025
  @override
2026 2027
  void initState() {
    super.initState();
2028 2029
    assert(widget.animationController.status == AnimationStatus.forward
        || widget.animationController.status == AnimationStatus.completed);
2030
    widget.animationController.addStatusListener(_handleStatusChange);
2031 2032
  }

2033
  @override
2034 2035 2036
  void didUpdateWidget(_PersistentBottomSheet oldWidget) {
    super.didUpdateWidget(oldWidget);
    assert(widget.animationController == oldWidget.animationController);
2037 2038 2039
  }

  void close() {
2040
    widget.animationController.reverse();
2041 2042
  }

2043
  void _handleStatusChange(AnimationStatus status) {
2044 2045
    if (status == AnimationStatus.dismissed && widget.onDismissed != null)
      widget.onDismissed();
2046 2047
  }

2048
  @override
2049
  Widget build(BuildContext context) {
2050
    return AnimatedBuilder(
2051
      animation: widget.animationController,
2052
      builder: (BuildContext context, Widget child) {
2053
        return Align(
2054
          alignment: AlignmentDirectional.topStart,
2055
          heightFactor: widget.animationController.value,
2056
          child: child,
2057
        );
2058
      },
2059
      child: Semantics(
Hixie's avatar
Hixie committed
2060
        container: true,
2061 2062 2063 2064
        onDismiss: () {
          close();
          widget.onClosing();
        },
2065
        child: BottomSheet(
2066
          animationController: widget.animationController,
2067
          enableDrag: widget.enableDrag,
2068
          onClosing: widget.onClosing,
2069 2070 2071
          builder: widget.builder,
        ),
      ),
2072 2073 2074 2075
    );
  }

}
2076 2077 2078

/// A [ScaffoldFeatureController] for persistent bottom sheets.
///
2079
/// This is the type of objects returned by [ScaffoldState.showBottomSheet].
2080 2081 2082 2083 2084
class PersistentBottomSheetController<T> extends ScaffoldFeatureController<_PersistentBottomSheet, T> {
  const PersistentBottomSheetController._(
    _PersistentBottomSheet widget,
    Completer<T> completer,
    VoidCallback close,
2085 2086
    StateSetter setState,
    this._isLocalHistoryEntry,
2087
  ) : super._(widget, completer, close, setState);
2088 2089

  final bool _isLocalHistoryEntry;
2090
}
2091 2092

class _ScaffoldScope extends InheritedWidget {
2093
  const _ScaffoldScope({
2094
    @required this.hasDrawer,
2095
    @required this.geometryNotifier,
2096
    @required Widget child,
2097 2098
  }) : assert(hasDrawer != null),
       super(child: child);
2099 2100

  final bool hasDrawer;
2101
  final _ScaffoldGeometryNotifier geometryNotifier;
2102 2103 2104 2105 2106

  @override
  bool updateShouldNotify(_ScaffoldScope oldWidget) {
    return hasDrawer != oldWidget.hasDrawer;
  }
2107
}