drawer.dart 8.94 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.

5
import 'package:flutter/widgets.dart';
6

7
import 'colors.dart';
8
import 'list_tile.dart';
9
import 'material.dart';
10 11

// TODO(eseidel): Draw width should vary based on device size:
12
// http://material.google.com/layout/structure.html#structure-side-nav
13 14 15 16 17 18 19 20 21 22 23 24

// Mobile:
// Width = Screen width − 56 dp
// Maximum width: 320dp
// Maximum width applies only when using a left nav. When using a right nav,
// the panel can cover the full width of the screen.

// Desktop/Tablet:
// Maximum width for a left nav is 400dp.
// The right nav can vary depending on content.

const double _kWidth = 304.0;
25
const double _kEdgeDragWidth = 20.0;
Matt Perry's avatar
Matt Perry committed
26
const double _kMinFlingVelocity = 365.0;
27 28
const Duration _kBaseSettleDuration = const Duration(milliseconds: 246);

29 30
/// A material design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
31
///
32 33
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/// that displays status information about the current user. The remaining
/// drawer children are often constructed with [ListTile]s, often concluding
/// with an [AboutListTile].
///
/// An open drawer can be closed by calling [Navigator.pop]. For example
/// a drawer item might close the drawer when tapped:
///
/// ```dart
/// new ListTile(
///   leading: new Icon(Icons.change_history),
///   title: new Text('Change history'),
///   onTap: () {
///     // change app state...
///     Navigator.pop(context); // close the drawer
///   },
/// );
/// ```
51
///
52 53 54
/// The [AppBar] automatically displays an appropriate [IconButton] to show the
/// [Drawer] when a [Drawer] is available in the [Scaffold]. The [Scaffold]
/// automatically handles the edge-swipe gesture to show the drawer.
55
///
56
/// See also:
57
///
58 59 60 61 62
///  * [Scaffold.drawer], where one specifies a [Drawer] so that it can be
///    shown.
///  * [Scaffold.of], to obtain the current [ScaffoldState], which manages the
///    display and animation of the drawer.
///  * [ScaffoldState.openDrawer], which displays its [Drawer], if any.
63
///  * <https://material.google.com/patterns/navigation-drawer.html>
64
class Drawer extends StatelessWidget {
65 66 67
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
68 69 70 71 72
  Drawer({
    Key key,
    this.elevation: 16,
    this.child
  }) : super(key: key);
73

74
  /// The z-coordinate at which to place this drawer.
75 76
  ///
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24
77 78
  ///
  /// Defaults to 16, the appropriate elevation for drawers.
Hans Muller's avatar
Hans Muller committed
79
  final int elevation;
80 81

  /// The widget below this widget in the tree.
82
  ///
83
  /// Typically a [SliverList].
84
  final Widget child;
85

86
  @override
87 88 89 90 91 92
  Widget build(BuildContext context) {
    return new ConstrainedBox(
      constraints: const BoxConstraints.expand(width: _kWidth),
      child: new Material(
        elevation: elevation,
        child: child
93
      )
94 95 96 97
    );
  }
}

98 99
/// Provides interactive behavior for [Drawer] widgets.
///
100 101 102 103 104 105 106
/// Rarely used directly. Drawer controllers are typically created automatically
/// by [Scaffold] widgets.
///
/// The draw controller provides the ability to open and close a drawer, either
/// via an animation or via user interaction. When closed, the drawer collapses
/// to a translucent gesture detector that can be used to listen for edge
/// swipes.
107 108
///
/// See also:
109
///
110 111
///  * [Drawer]
///  * [Scaffold.drawer]
112
class DrawerController extends StatefulWidget {
113 114 115 116 117
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
118 119
  DrawerController({
    GlobalKey key,
120
    this.child
121 122 123
  }) : super(key: key) {
    assert(child != null);
  }
124

125
  /// The widget below this widget in the tree.
126 127
  ///
  /// Typically a [Drawer].
128 129
  final Widget child;

130
  @override
131
  DrawerControllerState createState() => new DrawerControllerState();
132
}
133

134 135 136
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
137
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
138
  @override
139 140
  void initState() {
    super.initState();
141
    _controller = new AnimationController(duration: _kBaseSettleDuration, vsync: this)
142 143
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
144 145
  }

146
  @override
147
  void dispose() {
148
    _historyEntry?.remove();
149
    _controller.dispose();
150 151 152
    super.dispose();
  }

153
  void _animationChanged() {
154
    setState(() {
155
      // The animation controller's state is our build state, and it changed already.
156 157 158
    });
  }

159
  LocalHistoryEntry _historyEntry;
160
  // TODO(abarth): This should be a GlobalValueKey when those exist.
Hixie's avatar
Hixie committed
161
  GlobalKey get _drawerKey => new GlobalObjectKey(config.key);
162 163 164

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
165
      final ModalRoute<dynamic> route = ModalRoute.of(context);
166 167 168
      if (route != null) {
        _historyEntry = new LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
        route.addLocalHistoryEntry(_historyEntry);
Hixie's avatar
Hixie committed
169
        Focus.moveScopeTo(_drawerKey, context: context);
170 171 172 173
      }
    }
  }

174
  void _animationStatusChanged(AnimationStatus status) {
175
    switch (status) {
176
      case AnimationStatus.forward:
177 178
        _ensureHistoryEntry();
        break;
179
      case AnimationStatus.reverse:
180 181 182
        _historyEntry?.remove();
        _historyEntry = null;
        break;
183
      case AnimationStatus.dismissed:
184
        break;
185
      case AnimationStatus.completed:
186 187
        break;
    }
188 189
  }

190 191 192 193
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
194

195
  AnimationController _controller;
Hixie's avatar
Hixie committed
196

197
  void _handleDragDown(DragDownDetails details) {
198
    _controller.stop();
199
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
200 201
  }

202 203 204 205 206 207 208 209 210 211
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

Hixie's avatar
Hixie committed
212
  double get _width {
213
    final RenderBox drawerBox = _drawerKey.currentContext?.findRenderObject();
Hixie's avatar
Hixie committed
214 215 216 217 218
    if (drawerBox != null)
      return drawerBox.size.width;
    return _kWidth; // drawer not being shown currently
  }

219 220
  void _move(DragUpdateDetails details) {
    _controller.value += details.primaryDelta / _width;
221 222
  }

223
  void _settle(DragEndDetails details) {
224
    if (_controller.isDismissed)
225
      return;
226 227
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
      _controller.fling(velocity: details.velocity.pixelsPerSecond.dx / _width);
228
    } else if (_controller.value < 0.5) {
229
      close();
230
    } else {
231
      open();
232 233 234
    }
  }

235 236 237
  /// Starts an animation to open the drawer.
  ///
  /// Typically called by [Scaffold.openDrawer].
238
  void open() {
239
    _controller.fling(velocity: 1.0);
240 241
  }

242
  /// Starts an animation to close the drawer.
243
  void close() {
244
    _controller.fling(velocity: -1.0);
245
  }
246

247
  final ColorTween _color = new ColorTween(begin: Colors.transparent, end: Colors.black54);
248
  final GlobalKey _gestureDetectorKey = new GlobalKey();
249

250
  Widget _buildDrawer(BuildContext context) {
251
    if (_controller.status == AnimationStatus.dismissed) {
252
      return new Align(
253
        alignment: FractionalOffset.centerLeft,
254 255 256 257 258
        child: new GestureDetector(
          key: _gestureDetectorKey,
          onHorizontalDragUpdate: _move,
          onHorizontalDragEnd: _settle,
          behavior: HitTestBehavior.translucent,
Hixie's avatar
Hixie committed
259
          excludeFromSemantics: true,
260
          child: new Container(width: _kEdgeDragWidth)
261
        ),
262 263
      );
    } else {
264 265
      return new GestureDetector(
        key: _gestureDetectorKey,
266
        onHorizontalDragDown: _handleDragDown,
267 268
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
269
        onHorizontalDragCancel: _handleDragCancel,
270
        child: new RepaintBoundary(
271 272 273 274 275 276
          child: new Stack(
            children: <Widget>[
              new GestureDetector(
                onTap: close,
                child: new DecoratedBox(
                  decoration: new BoxDecoration(
277
                    backgroundColor: _color.evaluate(_controller)
278
                  ),
279 280
                  child: new Container(),
                ),
281 282
              ),
              new Align(
283
                alignment: FractionalOffset.centerLeft,
284
                child: new Align(
285
                  alignment: FractionalOffset.centerRight,
286 287 288 289 290
                  widthFactor: _controller.value,
                  child: new RepaintBoundary(
                    child: new Focus(
                      key: _drawerKey,
                      child: config.child
291 292 293 294 295 296 297
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
298 299
      );
    }
300
  }
301 302 303 304 305 306 307
  @override
  Widget build(BuildContext context) {
    return new ListTileTheme(
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
308
}