drawer.dart 7.73 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 'material.dart';
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

// TODO(eseidel): Draw width should vary based on device size:
// http://www.google.com/design/spec/layout/structure.html#structure-side-nav

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

28 29 30 31
/// A material design drawer.
///
/// Typically used in the [Scaffold.drawer] property, a drawer slides in from
/// the side of the screen and displays a list of items that the user can
32 33 34 35
/// interact with.
///
/// Typically, the child of the drawer is a [Block] whose first child is a
/// [DrawerHeader] that displays status information about the current user.
36 37
///
/// See also:
38
///
39 40 41 42
///  * [Scaffold.drawer]
///  * [DrawerItem]
///  * [DrawerHeader]
///  * <https://www.google.com/design/spec/patterns/navigation-drawer.html>
43
class Drawer extends StatelessWidget {
44 45 46
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
47 48 49 50 51
  Drawer({
    Key key,
    this.elevation: 16,
    this.child
  }) : super(key: key);
52

53
  /// The z-coordinate at which to place this drawer.
54 55
  ///
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24
Hans Muller's avatar
Hans Muller committed
56
  final int elevation;
57 58

  /// The widget below this widget in the tree.
59 60
  ///
  /// Typically a [Block].
61
  final Widget child;
62

63
  @override
64 65 66 67 68 69
  Widget build(BuildContext context) {
    return new ConstrainedBox(
      constraints: const BoxConstraints.expand(width: _kWidth),
      child: new Material(
        elevation: elevation,
        child: child
70
      )
71 72 73 74
    );
  }
}

75 76
/// Provides interactive behavior for [Drawer] widgets.
///
77 78 79 80 81 82 83
/// 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.
84 85
///
/// See also:
86
///
87 88
///  * [Drawer]
///  * [Scaffold.drawer]
89
class DrawerController extends StatefulWidget {
90 91 92 93 94
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
95 96
  DrawerController({
    GlobalKey key,
97
    this.child
98 99 100
  }) : super(key: key) {
    assert(child != null);
  }
101

102
  /// The widget below this widget in the tree.
103 104
  ///
  /// Typically a [Drawer].
105 106
  final Widget child;

107
  @override
108
  DrawerControllerState createState() => new DrawerControllerState();
109
}
110

111 112 113
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
114
class DrawerControllerState extends State<DrawerController> {
115
  @override
116 117
  void initState() {
    super.initState();
118 119 120
    _controller = new AnimationController(duration: _kBaseSettleDuration)
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
121 122
  }

123
  @override
124
  void dispose() {
125 126 127
    _controller
      ..removeListener(_animationChanged)
      ..removeStatusListener(_animationStatusChanged)
128 129 130 131
      ..stop();
    super.dispose();
  }

132
  void _animationChanged() {
133
    setState(() {
134
      // The animation controller's state is our build state, and it changed already.
135 136 137
    });
  }

138
  LocalHistoryEntry _historyEntry;
139
  // TODO(abarth): This should be a GlobalValueKey when those exist.
Hixie's avatar
Hixie committed
140
  GlobalKey get _drawerKey => new GlobalObjectKey(config.key);
141 142 143

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
144
      ModalRoute<dynamic> route = ModalRoute.of(context);
145 146 147
      if (route != null) {
        _historyEntry = new LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
        route.addLocalHistoryEntry(_historyEntry);
Hixie's avatar
Hixie committed
148
        Focus.moveScopeTo(_drawerKey, context: context);
149 150 151 152
      }
    }
  }

153
  void _animationStatusChanged(AnimationStatus status) {
154
    switch (status) {
155
      case AnimationStatus.forward:
156 157
        _ensureHistoryEntry();
        break;
158
      case AnimationStatus.reverse:
159 160 161
        _historyEntry?.remove();
        _historyEntry = null;
        break;
162
      case AnimationStatus.dismissed:
163
        break;
164
      case AnimationStatus.completed:
165 166
        break;
    }
167 168
  }

169 170 171 172
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
173

174
  AnimationController _controller;
Hixie's avatar
Hixie committed
175

176
  void _handleDragDown(Point position) {
177
    _controller.stop();
178
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
179 180
  }

181 182 183 184 185 186 187 188 189 190
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

Hixie's avatar
Hixie committed
191 192 193 194 195 196 197
  double get _width {
    RenderBox drawerBox = _drawerKey.currentContext?.findRenderObject();
    if (drawerBox != null)
      return drawerBox.size.width;
    return _kWidth; // drawer not being shown currently
  }

198
  void _move(double delta) {
199
    _controller.value += delta / _width;
200 201
  }

202
  void _settle(Velocity velocity) {
203
    if (_controller.isDismissed)
204
      return;
205 206
    if (velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
      _controller.fling(velocity: velocity.pixelsPerSecond.dx / _width);
207
    } else if (_controller.value < 0.5) {
208
      close();
209
    } else {
210
      open();
211 212 213
    }
  }

214 215 216
  /// Starts an animation to open the drawer.
  ///
  /// Typically called by [Scaffold.openDrawer].
217
  void open() {
218
    _controller.fling(velocity: 1.0);
219 220
  }

221
  /// Starts an animation to close the drawer.
222
  void close() {
223
    _controller.fling(velocity: -1.0);
224
  }
225

226
  final ColorTween _color = new ColorTween(begin: Colors.transparent, end: Colors.black54);
227
  final GlobalKey _gestureDetectorKey = new GlobalKey();
228

229
  @override
230
  Widget build(BuildContext context) {
231
    if (_controller.status == AnimationStatus.dismissed) {
232
      return new Align(
233
        alignment: FractionalOffset.centerLeft,
234 235 236 237 238
        child: new GestureDetector(
          key: _gestureDetectorKey,
          onHorizontalDragUpdate: _move,
          onHorizontalDragEnd: _settle,
          behavior: HitTestBehavior.translucent,
Hixie's avatar
Hixie committed
239
          excludeFromSemantics: true,
240 241
          child: new Container(width: _kEdgeDragWidth)
        )
242 243
      );
    } else {
244 245
      return new GestureDetector(
        key: _gestureDetectorKey,
246
        onHorizontalDragDown: _handleDragDown,
247 248
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
249
        onHorizontalDragCancel: _handleDragCancel,
250
        child: new RepaintBoundary(
251 252 253 254 255 256
          child: new Stack(
            children: <Widget>[
              new GestureDetector(
                onTap: close,
                child: new DecoratedBox(
                  decoration: new BoxDecoration(
257
                    backgroundColor: _color.evaluate(_controller)
258 259 260 261 262
                  ),
                  child: new Container()
                )
              ),
              new Align(
263
                alignment: FractionalOffset.centerLeft,
264
                child: new Align(
265
                  alignment: FractionalOffset.centerRight,
266 267 268 269 270
                  widthFactor: _controller.value,
                  child: new RepaintBoundary(
                    child: new Focus(
                      key: _drawerKey,
                      child: config.child
271 272
                    )
                  )
273
                )
274
              )
275 276
            ]
          )
277
        )
278 279
      );
    }
280
  }
281
}