drawer.dart 14.8 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 6
import 'dart:math';

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/widgets.dart';
9
import 'package:flutter/gestures.dart' show DragStartBehavior;
10

11
import 'colors.dart';
12
import 'debug.dart';
13
import 'list_tile.dart';
14
import 'material.dart';
15
import 'material_localizations.dart';
16

17
/// The possible alignments of a [Drawer].
18
enum DrawerAlignment {
19 20 21 22
  /// Denotes that the [Drawer] is at the start side of the [Scaffold].
  ///
  /// This corresponds to the left side when the text direction is left-to-right
  /// and the right side when the text direction is right-to-left.
23 24
  start,

25 26 27 28
  /// Denotes that the [Drawer] is at the end side of the [Scaffold].
  ///
  /// This corresponds to the right side when the text direction is left-to-right
  /// and the left side when the text direction is right-to-left.
29 30 31
  end,
}

32
// TODO(eseidel): Draw width should vary based on device size:
33
// https://material.io/design/components/navigation-drawer.html#specs
34 35 36 37 38 39 40 41 42 43 44 45

// 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;
46
const double _kEdgeDragWidth = 20.0;
Matt Perry's avatar
Matt Perry committed
47
const double _kMinFlingVelocity = 365.0;
48
const Duration _kBaseSettleDuration = Duration(milliseconds: 246);
49

50 51
/// A material design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
52
///
53 54
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
55 56 57 58 59 60 61 62
/// 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
63 64 65
/// ListTile(
///   leading: Icon(Icons.change_history),
///   title: Text('Change history'),
66 67 68 69 70 71
///   onTap: () {
///     // change app state...
///     Navigator.pop(context); // close the drawer
///   },
/// );
/// ```
72
///
73 74 75
/// 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.
76
///
77
/// See also:
78
///
79 80 81 82 83
///  * [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.
84
///  * <https://material.io/design/components/navigation-drawer.html>
85
class Drawer extends StatelessWidget {
86 87 88
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
89 90
  ///
  /// The [elevation] must be non-negative.
91
  const Drawer({
92
    Key key,
93
    this.elevation = 16.0,
94
    this.child,
95
    this.semanticLabel,
96 97
  }) : assert(elevation != null && elevation >= 0.0),
       super(key: key);
98

99 100 101
  /// The z-coordinate at which to place this drawer relative to its parent.
  ///
  /// This controls the size of the shadow below the drawer.
102
  ///
103 104
  /// Defaults to 16, the appropriate elevation for drawers. The value is
  /// always non-negative.
105
  final double elevation;
106 107

  /// The widget below this widget in the tree.
108
  ///
109
  /// Typically a [SliverList].
110 111
  ///
  /// {@macro flutter.widgets.child}
112
  final Widget child;
113

114
  /// The semantic label of the dialog used by accessibility frameworks to
115
  /// announce screen transitions when the drawer is opened and closed.
116
  ///
117 118
  /// If this label is not provided, it will default to
  /// [MaterialLocalizations.drawerLabel].
119
  ///
120
  /// See also:
121
  ///
122 123 124 125
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
  ///    value is used.
  final String semanticLabel;

126
  @override
127
  Widget build(BuildContext context) {
128
    assert(debugCheckHasMaterialLocalizations(context));
129 130 131 132 133 134 135 136 137
    String label = semanticLabel;
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
        label = semanticLabel;
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        label = semanticLabel ?? MaterialLocalizations.of(context)?.drawerLabel;
    }
138
    return Semantics(
139 140 141 142
      scopesRoute: true,
      namesRoute: true,
      explicitChildNodes: true,
      label: label,
143
      child: ConstrainedBox(
144
        constraints: const BoxConstraints.expand(width: _kWidth),
145
        child: Material(
146 147 148
          elevation: elevation,
          child: child,
        ),
149
      ),
150 151 152 153
    );
  }
}

jslavitz's avatar
jslavitz committed
154 155
/// Signature for the callback that's called when a [DrawerController] is
/// opened or closed.
156
typedef DrawerCallback = void Function(bool isOpened);
jslavitz's avatar
jslavitz committed
157

158 159
/// Provides interactive behavior for [Drawer] widgets.
///
160 161 162 163 164 165 166
/// 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.
167 168
///
/// See also:
169
///
170 171
///  * [Drawer], a container with the default width of a drawer.
///  * [Scaffold.drawer], the [Scaffold] slot for showing a drawer.
172
class DrawerController extends StatefulWidget {
173 174 175 176 177
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
178
  const DrawerController({
179
    GlobalKey key,
180
    @required this.child,
181
    @required this.alignment,
jslavitz's avatar
jslavitz committed
182
    this.drawerCallback,
183
    this.dragStartBehavior = DragStartBehavior.start,
184
  }) : assert(child != null),
185
       assert(dragStartBehavior != null),
186
       assert(alignment != null),
187
       super(key: key);
188

189
  /// The widget below this widget in the tree.
190 191
  ///
  /// Typically a [Drawer].
192 193
  final Widget child;

194
  /// The alignment of the [Drawer].
195
  ///
196 197
  /// This controls the direction in which the user should swipe to open and
  /// close the drawer.
198 199
  final DrawerAlignment alignment;

jslavitz's avatar
jslavitz committed
200 201 202
  /// Optional callback that is called when a [Drawer] is opened or closed.
  final DrawerCallback drawerCallback;

203 204 205 206 207 208 209 210 211 212 213 214
  /// {@template flutter.material.drawer.dragStartBehavior}
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], the drag behavior used for opening
  /// and closing a drawer will begin upon the detection of a drag gesture. If
  /// set to [DragStartBehavior.down] it will begin when a down event is first
  /// detected.
  ///
  /// In general, setting this to [DragStartBehavior.start] will make drag
  /// animation smoother and setting it to [DragStartBehavior.down] will make
  /// drag behavior feel slightly more reactive.
  ///
215
  /// By default, the drag start behavior is [DragStartBehavior.start].
216 217 218 219 220 221 222
  ///
  /// See also:
  ///
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

223
  @override
224
  DrawerControllerState createState() => DrawerControllerState();
225
}
226

227 228 229
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
230
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
231
  @override
232 233
  void initState() {
    super.initState();
234
    _controller = AnimationController(duration: _kBaseSettleDuration, vsync: this)
235 236
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
237 238
  }

239
  @override
240
  void dispose() {
241
    _historyEntry?.remove();
242
    _controller.dispose();
243 244 245
    super.dispose();
  }

246
  void _animationChanged() {
247
    setState(() {
248
      // The animation controller's state is our build state, and it changed already.
249 250 251
    });
  }

252
  LocalHistoryEntry _historyEntry;
253
  final FocusScopeNode _focusScopeNode = FocusScopeNode();
254 255 256

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
257
      final ModalRoute<dynamic> route = ModalRoute.of(context);
258
      if (route != null) {
259
        _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
260
        route.addLocalHistoryEntry(_historyEntry);
261
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
262 263 264 265
      }
    }
  }

266
  void _animationStatusChanged(AnimationStatus status) {
267
    switch (status) {
268
      case AnimationStatus.forward:
269 270
        _ensureHistoryEntry();
        break;
271
      case AnimationStatus.reverse:
272 273 274
        _historyEntry?.remove();
        _historyEntry = null;
        break;
275
      case AnimationStatus.dismissed:
276
        break;
277
      case AnimationStatus.completed:
278 279
        break;
    }
280 281
  }

282 283 284 285
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
286

287
  AnimationController _controller;
Hixie's avatar
Hixie committed
288

289
  void _handleDragDown(DragDownDetails details) {
290
    _controller.stop();
291
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
292 293
  }

294 295 296 297 298 299 300 301 302 303
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

304
  final GlobalKey _drawerKey = GlobalKey();
305

Hixie's avatar
Hixie committed
306
  double get _width {
307 308 309
    final RenderBox box = _drawerKey.currentContext?.findRenderObject();
    if (box != null)
      return box.size.width;
Hixie's avatar
Hixie committed
310 311 312
    return _kWidth; // drawer not being shown currently
  }

jslavitz's avatar
jslavitz committed
313 314
  bool _previouslyOpened = false;

315
  void _move(DragUpdateDetails details) {
316 317 318 319 320 321 322 323
    double delta = details.primaryDelta / _width;
    switch (widget.alignment) {
      case DrawerAlignment.start:
        break;
      case DrawerAlignment.end:
        delta = -delta;
        break;
    }
324 325 326 327 328 329 330 331
    switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.value -= delta;
        break;
      case TextDirection.ltr:
        _controller.value += delta;
        break;
    }
jslavitz's avatar
jslavitz committed
332 333 334 335 336

    final bool opened = _controller.value > 0.5 ? true : false;
    if (opened != _previouslyOpened && widget.drawerCallback != null)
      widget.drawerCallback(opened);
    _previouslyOpened = opened;
337 338
  }

339
  void _settle(DragEndDetails details) {
340
    if (_controller.isDismissed)
341
      return;
342
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
343 344 345 346 347 348 349 350
      double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
      switch (widget.alignment) {
        case DrawerAlignment.start:
          break;
        case DrawerAlignment.end:
          visualVelocity = -visualVelocity;
          break;
      }
351 352 353 354 355 356 357
      switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.fling(velocity: -visualVelocity);
        break;
      case TextDirection.ltr:
        _controller.fling(velocity: visualVelocity);
        break;
358
      }
359
    } else if (_controller.value < 0.5) {
360
      close();
361
    } else {
362
      open();
363 364 365
    }
  }

366 367
  /// Starts an animation to open the drawer.
  ///
368
  /// Typically called by [ScaffoldState.openDrawer].
369
  void open() {
370
    _controller.fling(velocity: 1.0);
jslavitz's avatar
jslavitz committed
371 372
    if (widget.drawerCallback != null)
      widget.drawerCallback(true);
373 374
  }

375
  /// Starts an animation to close the drawer.
376
  void close() {
377
    _controller.fling(velocity: -1.0);
jslavitz's avatar
jslavitz committed
378 379
    if (widget.drawerCallback != null)
      widget.drawerCallback(false);
380
  }
381

382 383
  final ColorTween _color = ColorTween(begin: Colors.transparent, end: Colors.black54);
  final GlobalKey _gestureDetectorKey = GlobalKey();
384

385
  AlignmentDirectional get _drawerOuterAlignment {
386
    assert(widget.alignment != null);
387 388 389 390 391 392
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerStart;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerEnd;
    }
393
    return null;
394 395 396
  }

  AlignmentDirectional get _drawerInnerAlignment {
397
    assert(widget.alignment != null);
398 399 400 401 402 403
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerEnd;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerStart;
    }
404
    return null;
405 406
  }

407
  Widget _buildDrawer(BuildContext context) {
408 409 410 411 412 413 414 415
    final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
    final EdgeInsets padding = MediaQuery.of(context).padding;
    double dragAreaWidth = drawerIsStart ? padding.left : padding.right;

    if (Directionality.of(context) == TextDirection.rtl)
      dragAreaWidth = drawerIsStart ? padding.right : padding.left;

    dragAreaWidth = max(dragAreaWidth, _kEdgeDragWidth);
416
    if (_controller.status == AnimationStatus.dismissed) {
417
      return Align(
418
        alignment: _drawerOuterAlignment,
419
        child: GestureDetector(
420 421 422 423
          key: _gestureDetectorKey,
          onHorizontalDragUpdate: _move,
          onHorizontalDragEnd: _settle,
          behavior: HitTestBehavior.translucent,
Hixie's avatar
Hixie committed
424
          excludeFromSemantics: true,
425
          dragStartBehavior: widget.dragStartBehavior,
426
          child: Container(width: dragAreaWidth),
427
        ),
428 429
      );
    } else {
430
      return GestureDetector(
431
        key: _gestureDetectorKey,
432
        onHorizontalDragDown: _handleDragDown,
433 434
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
435
        onHorizontalDragCancel: _handleDragCancel,
436
        excludeFromSemantics: true,
437
        dragStartBehavior: widget.dragStartBehavior,
438 439
        child: RepaintBoundary(
          child: Stack(
440
            children: <Widget>[
441 442
              BlockSemantics(
                child: GestureDetector(
443 444
                  // On Android, the back button is used to dismiss a modal.
                  excludeFromSemantics: defaultTargetPlatform == TargetPlatform.android,
445
                  onTap: close,
446
                  child: Semantics(
447
                    label: MaterialLocalizations.of(context)?.modalBarrierDismissLabel,
448
                    child: Container(
449 450
                      color: _color.evaluate(_controller),
                    ),
451
                  ),
452
                ),
453
              ),
454
              Align(
455
                alignment: _drawerOuterAlignment,
456
                child: Align(
457
                  alignment: _drawerInnerAlignment,
458
                  widthFactor: _controller.value,
459 460
                  child: RepaintBoundary(
                    child: FocusScope(
461
                      key: _drawerKey,
462
                      node: _focusScopeNode,
463
                      child: widget.child,
464 465 466 467 468 469 470
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
471 472
      );
    }
473
  }
474 475
  @override
  Widget build(BuildContext context) {
476
    assert(debugCheckHasMaterialLocalizations(context));
477
    return ListTileTheme(
478 479 480 481
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
482
}