drawer.dart 8.82 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/foundation.dart';
6
import 'package:flutter/widgets.dart';
7

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

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

// 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;
26
const double _kEdgeDragWidth = 20.0;
Matt Perry's avatar
Matt Perry committed
27
const double _kMinFlingVelocity = 365.0;
28 29
const Duration _kBaseSettleDuration = const Duration(milliseconds: 246);

30 31
/// A material design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
32
///
33 34
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/// 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
///   },
/// );
/// ```
52
///
53 54 55
/// 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.
56
///
57
/// See also:
58
///
59 60 61 62 63
///  * [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.
64
///  * <https://material.google.com/patterns/navigation-drawer.html>
65
class Drawer extends StatelessWidget {
66 67 68
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
69
  const Drawer({
70
    Key key,
71
    this.elevation: 16.0,
72 73
    this.child
  }) : super(key: key);
74

75
  /// The z-coordinate at which to place this drawer.
76
  ///
77
  /// Defaults to 16, the appropriate elevation for drawers.
78
  final double elevation;
79 80

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

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

97 98
/// Provides interactive behavior for [Drawer] widgets.
///
99 100 101 102 103 104 105
/// 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.
106 107
///
/// See also:
108
///
109 110
///  * [Drawer]
///  * [Scaffold.drawer]
111
class DrawerController extends StatefulWidget {
112 113 114 115 116
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
117
  const DrawerController({
118
    GlobalKey key,
119
    @required this.child
120 121
  }) : assert(child != null),
       super(key: key);
122

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

128
  @override
129
  DrawerControllerState createState() => new DrawerControllerState();
130
}
131

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

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

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

157
  LocalHistoryEntry _historyEntry;
158
  final FocusScopeNode _focusScopeNode = new FocusScopeNode();
159 160 161

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
162
      final ModalRoute<dynamic> route = ModalRoute.of(context);
163 164 165
      if (route != null) {
        _historyEntry = new LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
        route.addLocalHistoryEntry(_historyEntry);
166
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
167 168 169 170
      }
    }
  }

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

187 188 189 190
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
191

192
  AnimationController _controller;
Hixie's avatar
Hixie committed
193

194
  void _handleDragDown(DragDownDetails details) {
195
    _controller.stop();
196
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
197 198
  }

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

209 210
  final GlobalKey _drawerKey = new GlobalKey();

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

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

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

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

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

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

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