bottom_sheet.dart 8.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// 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.

import 'dart:async';

import 'package:flutter/widgets.dart';

import 'colors.dart';
import 'material.dart';
11
import 'theme.dart';
12 13

const Duration _kBottomSheetDuration = const Duration(milliseconds: 200);
14
const double _kMinFlingVelocity = 700.0;
15
const double _kCloseProgressThreshold = 0.5;
16 17
const Color _kTransparent = const Color(0x00000000);
const Color _kBarrierColor = Colors.black54;
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/// A material design bottom sheet.
///
/// There are two kinds of bottom sheets in material design:
///
///  * _Persistent_. 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.
///    Persistent bottom sheets can be created and displayed with the
///    [Scaffold.showBottomSheet] function.
///
///  * _Modal_. A modal bottom sheet 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.
///
/// The [BottomSheet] widget itself is rarely used directly. Instead, prefer to
/// create a persistent bottom sheet with [Scaffold.showBottomSheet] and a modal
/// bottom sheet with [showModalBottomSheet].
///
/// See also:
///
///  * [Scaffold.showBottomSheet]
///  * [showModalBottomSheet]
42
///  * <https://material.google.com/components/bottom-sheets.html>
43
class BottomSheet extends StatefulWidget {
44 45 46 47 48
  /// Creates a bottom sheet.
  ///
  /// Typically, bottom sheets are created implicitly by
  /// [Scaffold.showBottomSheet], for persistent bottom sheets, or by
  /// [showModalBottomSheet], for modal bottom sheets.
49
  BottomSheet({
50
    Key key,
51
    this.animationController,
52 53 54 55
    this.onClosing,
    this.builder
  }) : super(key: key) {
    assert(onClosing != null);
56
    assert(builder != null);
57
  }
58

59 60 61 62
  /// The animation that controls the bottom sheet's position.
  ///
  /// The BottomSheet widget will manipulate the position of this animation, it
  /// is not just a passive observer.
63
  final AnimationController animationController;
64 65 66 67 68 69

  /// Called when the bottom sheet begins to close.
  ///
  /// A bottom sheet might be be prevented from closing (e.g., by user
  /// interaction) even after this callback is called. For this reason, this
  /// callback might be call multiple times for a given bottom sheet.
70
  final VoidCallback onClosing;
71 72 73 74 75

  /// A builder for the contents of the sheet.
  ///
  /// The bottom sheet will wrap the widget produced by this builder in a
  /// [Material] widget.
76 77
  final WidgetBuilder builder;

78
  @override
79 80
  _BottomSheetState createState() => new _BottomSheetState();

81
  /// Creates an animation controller suitable for controlling a [BottomSheet].
82
  static AnimationController createAnimationController(TickerProvider vsync) {
83
    return new AnimationController(
84
      duration: _kBottomSheetDuration,
85 86
      debugLabel: 'BottomSheet',
      vsync: vsync,
87 88
    );
  }
89 90 91 92
}

class _BottomSheetState extends State<BottomSheet> {

93
  final GlobalKey _childKey = new GlobalKey(debugLabel: 'BottomSheet child');
94 95 96 97 98

  double get _childHeight {
    final RenderBox renderBox = _childKey.currentContext.findRenderObject();
    return renderBox.size.height;
  }
99

Adam Barth's avatar
Adam Barth committed
100
  bool get _dismissUnderway => config.animationController.status == AnimationStatus.reverse;
101

102
  void _handleDragUpdate(DragUpdateDetails details) {
103 104
    if (_dismissUnderway)
      return;
105
    config.animationController.value -= details.primaryDelta / (_childHeight ?? details.primaryDelta);
106 107
  }

108
  void _handleDragEnd(DragEndDetails details) {
109 110
    if (_dismissUnderway)
      return;
111 112
    if (details.velocity.pixelsPerSecond.dy > _kMinFlingVelocity) {
      double flingVelocity = -details.velocity.pixelsPerSecond.dy / _childHeight;
113 114
      if (config.animationController.value > 0.0)
        config.animationController.fling(velocity: flingVelocity);
115
      if (flingVelocity < 0.0)
116
        config.onClosing();
117
    } else if (config.animationController.value < _kCloseProgressThreshold) {
118 119
      if (config.animationController.value > 0.0)
        config.animationController.fling(velocity: -1.0);
120
      config.onClosing();
121
    } else {
122
      config.animationController.forward();
123
    }
124 125
  }

126
  @override
127 128 129
  Widget build(BuildContext context) {
    return new GestureDetector(
      onVerticalDragUpdate: _handleDragUpdate,
130
      onVerticalDragEnd: _handleDragEnd,
131
      child: new Material(
132
        key: _childKey,
133
        child: config.builder(context)
134
      )
135 136 137 138
    );
  }
}

139
// PERSISTENT BOTTOM SHEETS
140

141
// See scaffold.dart
142 143


144
// MODAL BOTTOM SHEETS
145

146
class _ModalBottomSheetLayout extends SingleChildLayoutDelegate {
147 148 149
  _ModalBottomSheetLayout(this.progress);

  final double progress;
150

151
  @override
152 153 154 155 156 157 158 159 160
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return new BoxConstraints(
      minWidth: constraints.maxWidth,
      maxWidth: constraints.maxWidth,
      minHeight: 0.0,
      maxHeight: constraints.maxHeight * 9.0 / 16.0
    );
  }

161
  @override
162 163
  Offset getPositionForChild(Size size, Size childSize) {
    return new Offset(0.0, size.height - childSize.height * progress);
164 165
  }

166
  @override
167 168
  bool shouldRelayout(_ModalBottomSheetLayout oldDelegate) {
    return progress != oldDelegate.progress;
169 170 171
  }
}

172
class _ModalBottomSheet<T> extends StatefulWidget {
173 174
  _ModalBottomSheet({ Key key, this.route }) : super(key: key);

175
  final _ModalBottomSheetRoute<T> route;
176

177
  @override
178
  _ModalBottomSheetState<T> createState() => new _ModalBottomSheetState<T>();
179 180
}

181
class _ModalBottomSheetState<T> extends State<_ModalBottomSheet<T>> {
182
  @override
183
  Widget build(BuildContext context) {
184
    return new GestureDetector(
Hixie's avatar
Hixie committed
185
      onTap: () => Navigator.pop(context),
186
      child: new AnimatedBuilder(
187
        animation: config.route.animation,
188
        builder: (BuildContext context, Widget child) {
189
          return new ClipRect(
190
            child: new CustomSingleChildLayout(
191
              delegate: new _ModalBottomSheetLayout(config.route.animation.value),
192
              child: new BottomSheet(
193
                animationController: config.route._animationController,
Hixie's avatar
Hixie committed
194
                onClosing: () => Navigator.pop(context),
195
                builder: config.route.builder
196
              )
197
            )
198 199 200
          );
        }
      )
201 202 203 204
    );
  }
}

Hixie's avatar
Hixie committed
205 206
class _ModalBottomSheetRoute<T> extends PopupRoute<T> {
  _ModalBottomSheetRoute({
207 208
    this.builder,
    this.theme,
209
  });
210 211

  final WidgetBuilder builder;
212
  final ThemeData theme;
213

214
  @override
Hixie's avatar
Hixie committed
215
  Duration get transitionDuration => _kBottomSheetDuration;
216 217

  @override
Hixie's avatar
Hixie committed
218
  bool get barrierDismissable => true;
219 220

  @override
Hixie's avatar
Hixie committed
221
  Color get barrierColor => Colors.black54;
222

223 224
  AnimationController _animationController;

225
  @override
226
  AnimationController createAnimationController() {
227
    assert(_animationController == null);
228
    _animationController = BottomSheet.createAnimationController(navigator.overlay);
229
    return _animationController;
230 231
  }

232
  @override
233
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation) {
234 235 236 237
    Widget bottomSheet = new _ModalBottomSheet<T>(route: this);
    if (theme != null)
      bottomSheet = new Theme(data: theme, child: bottomSheet);
    return bottomSheet;
238 239 240
  }
}

241 242 243 244 245 246 247 248 249 250 251
/// Shows a modal material design bottom sheet.
///
/// A modal bottom sheet is an alternative to a menu or a dialog and prevents
/// the user from interacting with the rest of the app.
///
/// A closely related widget is a persistent bottom sheet, which shows
/// information that supplements the primary content of the app without
/// preventing the use from interacting with the app. Persistent bottom sheets
/// can be created and displayed with the [Scaffold.showBottomSheet] function.
///
/// Returns a `Future` that resolves to the value (if any) that was passed to
252
/// [Navigator.pop] when the modal bottom sheet was closed.
253 254 255 256 257
///
/// See also:
///
///  * [BottomSheet]
///  * [Scaffold.showBottomSheet]
258
///  * <https://material.google.com/components/bottom-sheets.html#bottom-sheets-modal-bottom-sheets>
259
Future<dynamic/*=T*/> showModalBottomSheet/*<T>*/({ BuildContext context, WidgetBuilder builder }) {
260 261
  assert(context != null);
  assert(builder != null);
262
  return Navigator.push(context, new _ModalBottomSheetRoute<dynamic/*=T*/>(
263 264
    builder: builder,
    theme: Theme.of(context, shadowThemeOnly: true),
265 266
  ));
}