drawer.dart 18.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// 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
import 'package:flutter/gestures.dart' show DragStartBehavior;
8

9
import 'colors.dart';
10
import 'debug.dart';
11
import 'list_tile.dart';
12
import 'material.dart';
13
import 'material_localizations.dart';
14
import 'theme.dart';
15

16
/// The possible alignments of a [Drawer].
17
enum DrawerAlignment {
18 19 20 21
  /// 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.
22 23
  start,

24 25 26 27
  /// 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.
28 29 30
  end,
}

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

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

49 50
/// A material design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
51
///
52 53
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
54 55 56 57
/// that displays status information about the current user. The remaining
/// drawer children are often constructed with [ListTile]s, often concluding
/// with an [AboutListTile].
///
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/// 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.
///
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/drawer.mp4}
///
/// {@tool sample}
/// This example shows how to create a [Scaffold] that contains an [AppBar] and
/// a [Drawer]. A user taps the "menu" icon in the [AppBar] to open the
/// [Drawer]. The [Drawer] displays four items: A header and three menu items.
/// The [Drawer] displays the four items using a [ListView], which allows the
/// user to scroll through the items if need be.
///
/// ```dart
/// Scaffold(
///   appBar: AppBar(
///     title: const Text('Drawer Demo'),
///   ),
///   drawer: Drawer(
///     child: ListView(
///       padding: EdgeInsets.zero,
///       children: const <Widget>[
///         DrawerHeader(
///           decoration: BoxDecoration(
///             color: Colors.blue,
///           ),
///           child: Text(
///             'Drawer Header',
///             style: TextStyle(
///               color: Colors.white,
///               fontSize: 24,
///             ),
///           ),
///         ),
///         ListTile(
///           leading: Icon(Icons.message),
///           title: Text('Messages'),
///         ),
///         ListTile(
///           leading: Icon(Icons.account_circle),
///           title: Text('Profile'),
///         ),
///         ListTile(
///           leading: Icon(Icons.settings),
///           title: Text('Settings'),
///         ),
///       ],
///     ),
///   ),
/// )
/// ```
/// {@end-tool}
///
111 112 113 114
/// An open drawer can be closed by calling [Navigator.pop]. For example
/// a drawer item might close the drawer when tapped:
///
/// ```dart
115 116 117
/// ListTile(
///   leading: Icon(Icons.change_history),
///   title: Text('Change history'),
118 119 120 121 122 123
///   onTap: () {
///     // change app state...
///     Navigator.pop(context); // close the drawer
///   },
/// );
/// ```
124
///
125
/// See also:
126
///
127 128 129 130 131
///  * [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.
132
///  * <https://material.io/design/components/navigation-drawer.html>
133
class Drawer extends StatelessWidget {
134 135 136
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
137 138
  ///
  /// The [elevation] must be non-negative.
139
  const Drawer({
140
    Key key,
141
    this.elevation = 16.0,
142
    this.child,
143
    this.semanticLabel,
144 145
  }) : assert(elevation != null && elevation >= 0.0),
       super(key: key);
146

147 148 149
  /// The z-coordinate at which to place this drawer relative to its parent.
  ///
  /// This controls the size of the shadow below the drawer.
150
  ///
151 152
  /// Defaults to 16, the appropriate elevation for drawers. The value is
  /// always non-negative.
153
  final double elevation;
154 155

  /// The widget below this widget in the tree.
156
  ///
157
  /// Typically a [SliverList].
158 159
  ///
  /// {@macro flutter.widgets.child}
160
  final Widget child;
161

162
  /// The semantic label of the dialog used by accessibility frameworks to
163
  /// announce screen transitions when the drawer is opened and closed.
164
  ///
165 166
  /// If this label is not provided, it will default to
  /// [MaterialLocalizations.drawerLabel].
167
  ///
168
  /// See also:
169
  ///
170 171 172 173
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
  ///    value is used.
  final String semanticLabel;

174
  @override
175
  Widget build(BuildContext context) {
176
    assert(debugCheckHasMaterialLocalizations(context));
177
    String label = semanticLabel;
178
    switch (Theme.of(context).platform) {
179
      case TargetPlatform.iOS:
180
      case TargetPlatform.macOS:
181 182 183 184 185 186
        label = semanticLabel;
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        label = semanticLabel ?? MaterialLocalizations.of(context)?.drawerLabel;
    }
187
    return Semantics(
188 189 190 191
      scopesRoute: true,
      namesRoute: true,
      explicitChildNodes: true,
      label: label,
192
      child: ConstrainedBox(
193
        constraints: const BoxConstraints.expand(width: _kWidth),
194
        child: Material(
195 196 197
          elevation: elevation,
          child: child,
        ),
198
      ),
199 200 201 202
    );
  }
}

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

207 208
/// Provides interactive behavior for [Drawer] widgets.
///
209 210 211 212 213 214 215
/// 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.
216 217
///
/// See also:
218
///
219 220
///  * [Drawer], a container with the default width of a drawer.
///  * [Scaffold.drawer], the [Scaffold] slot for showing a drawer.
221
class DrawerController extends StatefulWidget {
222 223 224 225 226
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
227
  const DrawerController({
228
    GlobalKey key,
229
    @required this.child,
230
    @required this.alignment,
jslavitz's avatar
jslavitz committed
231
    this.drawerCallback,
232
    this.dragStartBehavior = DragStartBehavior.start,
233
    this.scrimColor,
234
    this.edgeDragWidth,
235
  }) : assert(child != null),
236
       assert(dragStartBehavior != null),
237
       assert(alignment != null),
238
       super(key: key);
239

240
  /// The widget below this widget in the tree.
241 242
  ///
  /// Typically a [Drawer].
243 244
  final Widget child;

245
  /// The alignment of the [Drawer].
246
  ///
247 248
  /// This controls the direction in which the user should swipe to open and
  /// close the drawer.
249 250
  final DrawerAlignment alignment;

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

254 255 256 257 258 259 260 261 262 263 264 265
  /// {@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.
  ///
266
  /// By default, the drag start behavior is [DragStartBehavior.start].
267 268 269
  ///
  /// See also:
  ///
270 271 272
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
273 274 275
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

276 277
  /// The color to use for the scrim that obscures primary content while a drawer is open.
  ///
278
  /// By default, the color used is [Colors.black54]
279 280
  final Color scrimColor;

281 282 283 284 285 286 287 288 289 290 291
  /// The width of the area within which a horizontal swipe will open the
  /// drawer.
  ///
  /// By default, the value used is 20.0 added to the padding edge of
  /// `MediaQuery.of(context).padding` that corresponds to [alignment].
  /// This ensures that the drag area for notched devices is not obscured. For
  /// example, if [alignment] is set to [DrawerAlignment.start] and
  /// `TextDirection.of(context)` is set to [TextDirection.ltr],
  /// 20.0 will be added to `MediaQuery.of(context).padding.left`.
  final double edgeDragWidth;

292
  @override
293
  DrawerControllerState createState() => DrawerControllerState();
294
}
295

296 297 298
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
299
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
300
  @override
301 302
  void initState() {
    super.initState();
303
    _scrimColorTween = _buildScrimColorTween();
304
    _controller = AnimationController(duration: _kBaseSettleDuration, vsync: this)
305 306
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
307 308
  }

309
  @override
310
  void dispose() {
311
    _historyEntry?.remove();
312
    _controller.dispose();
313 314 315
    super.dispose();
  }

316 317 318 319 320 321 322
  @override
  void didUpdateWidget(DrawerController oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.scrimColor != oldWidget.scrimColor)
      _scrimColorTween = _buildScrimColorTween();
  }

323
  void _animationChanged() {
324
    setState(() {
325
      // The animation controller's state is our build state, and it changed already.
326 327 328
    });
  }

329
  LocalHistoryEntry _historyEntry;
330
  final FocusScopeNode _focusScopeNode = FocusScopeNode();
331 332 333

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
334
      final ModalRoute<dynamic> route = ModalRoute.of(context);
335
      if (route != null) {
336
        _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
337
        route.addLocalHistoryEntry(_historyEntry);
338
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
339 340 341 342
      }
    }
  }

343
  void _animationStatusChanged(AnimationStatus status) {
344
    switch (status) {
345
      case AnimationStatus.forward:
346 347
        _ensureHistoryEntry();
        break;
348
      case AnimationStatus.reverse:
349 350 351
        _historyEntry?.remove();
        _historyEntry = null;
        break;
352
      case AnimationStatus.dismissed:
353
        break;
354
      case AnimationStatus.completed:
355 356
        break;
    }
357 358
  }

359 360 361 362
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
363

364
  AnimationController _controller;
Hixie's avatar
Hixie committed
365

366
  void _handleDragDown(DragDownDetails details) {
367
    _controller.stop();
368
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
369 370
  }

371 372 373 374 375 376 377 378 379 380
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

381
  final GlobalKey _drawerKey = GlobalKey();
382

Hixie's avatar
Hixie committed
383
  double get _width {
384
    final RenderBox box = _drawerKey.currentContext?.findRenderObject() as RenderBox;
385 386
    if (box != null)
      return box.size.width;
Hixie's avatar
Hixie committed
387 388 389
    return _kWidth; // drawer not being shown currently
  }

jslavitz's avatar
jslavitz committed
390 391
  bool _previouslyOpened = false;

392
  void _move(DragUpdateDetails details) {
393 394 395 396 397 398 399 400
    double delta = details.primaryDelta / _width;
    switch (widget.alignment) {
      case DrawerAlignment.start:
        break;
      case DrawerAlignment.end:
        delta = -delta;
        break;
    }
401 402 403 404 405 406 407 408
    switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.value -= delta;
        break;
      case TextDirection.ltr:
        _controller.value += delta;
        break;
    }
jslavitz's avatar
jslavitz committed
409

410
    final bool opened = _controller.value > 0.5;
jslavitz's avatar
jslavitz committed
411 412 413
    if (opened != _previouslyOpened && widget.drawerCallback != null)
      widget.drawerCallback(opened);
    _previouslyOpened = opened;
414 415
  }

416
  void _settle(DragEndDetails details) {
417
    if (_controller.isDismissed)
418
      return;
419
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
420 421 422 423 424 425 426 427
      double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
      switch (widget.alignment) {
        case DrawerAlignment.start:
          break;
        case DrawerAlignment.end:
          visualVelocity = -visualVelocity;
          break;
      }
428
      switch (Directionality.of(context)) {
429 430 431 432 433 434
        case TextDirection.rtl:
          _controller.fling(velocity: -visualVelocity);
          break;
        case TextDirection.ltr:
          _controller.fling(velocity: visualVelocity);
          break;
435
      }
436
    } else if (_controller.value < 0.5) {
437
      close();
438
    } else {
439
      open();
440 441 442
    }
  }

443 444
  /// Starts an animation to open the drawer.
  ///
445
  /// Typically called by [ScaffoldState.openDrawer].
446
  void open() {
447
    _controller.fling(velocity: 1.0);
jslavitz's avatar
jslavitz committed
448 449
    if (widget.drawerCallback != null)
      widget.drawerCallback(true);
450 451
  }

452
  /// Starts an animation to close the drawer.
453
  void close() {
454
    _controller.fling(velocity: -1.0);
jslavitz's avatar
jslavitz committed
455 456
    if (widget.drawerCallback != null)
      widget.drawerCallback(false);
457
  }
458

459
  ColorTween _scrimColorTween;
460
  final GlobalKey _gestureDetectorKey = GlobalKey();
461

462 463 464 465
  ColorTween _buildScrimColorTween() {
    return ColorTween(begin: Colors.transparent, end: widget.scrimColor ?? Colors.black54);
  }

466
  AlignmentDirectional get _drawerOuterAlignment {
467
    assert(widget.alignment != null);
468 469 470 471 472 473
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerStart;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerEnd;
    }
474
    return null;
475 476 477
  }

  AlignmentDirectional get _drawerInnerAlignment {
478
    assert(widget.alignment != null);
479 480 481 482 483 484
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerEnd;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerStart;
    }
485
    return null;
486 487
  }

488
  Widget _buildDrawer(BuildContext context) {
489 490
    final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
    final EdgeInsets padding = MediaQuery.of(context).padding;
491 492 493 494 495
    final TextDirection textDirection = Directionality.of(context);

    double dragAreaWidth = widget.edgeDragWidth;
    if (widget.edgeDragWidth == null) {
      switch (textDirection) {
496
        case TextDirection.ltr:
497 498
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.left : padding.right);
499 500
          break;
        case TextDirection.rtl:
501 502
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.right : padding.left);
503
          break;
504 505
      }
    }
506

507
    if (_controller.status == AnimationStatus.dismissed) {
508
      return Align(
509
        alignment: _drawerOuterAlignment,
510
        child: GestureDetector(
511 512 513 514
          key: _gestureDetectorKey,
          onHorizontalDragUpdate: _move,
          onHorizontalDragEnd: _settle,
          behavior: HitTestBehavior.translucent,
Hixie's avatar
Hixie committed
515
          excludeFromSemantics: true,
516
          dragStartBehavior: widget.dragStartBehavior,
517
          child: Container(width: dragAreaWidth),
518
        ),
519 520
      );
    } else {
521 522 523 524 525 526
      bool platformHasBackButton;
      switch (Theme.of(context).platform) {
        case TargetPlatform.android:
          platformHasBackButton = true;
          break;
        case TargetPlatform.iOS:
527
        case TargetPlatform.macOS:
528 529 530 531 532
        case TargetPlatform.fuchsia:
          platformHasBackButton = false;
          break;
      }
      assert(platformHasBackButton != null);
533
      return GestureDetector(
534
        key: _gestureDetectorKey,
535
        onHorizontalDragDown: _handleDragDown,
536 537
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
538
        onHorizontalDragCancel: _handleDragCancel,
539
        excludeFromSemantics: true,
540
        dragStartBehavior: widget.dragStartBehavior,
541 542
        child: RepaintBoundary(
          child: Stack(
543
            children: <Widget>[
544 545
              BlockSemantics(
                child: GestureDetector(
546
                  // On Android, the back button is used to dismiss a modal.
547
                  excludeFromSemantics: platformHasBackButton,
548
                  onTap: close,
549
                  child: Semantics(
550
                    label: MaterialLocalizations.of(context)?.modalBarrierDismissLabel,
551 552 553 554 555 556
                    child: MouseRegion(
                      opaque: true,
                      child: Container( // The drawer's "scrim"
                        color: _scrimColorTween.evaluate(_controller),
                      ),
                    )
557
                  ),
558
                ),
559
              ),
560
              Align(
561
                alignment: _drawerOuterAlignment,
562
                child: Align(
563
                  alignment: _drawerInnerAlignment,
564
                  widthFactor: _controller.value,
565 566
                  child: RepaintBoundary(
                    child: FocusScope(
567
                      key: _drawerKey,
568
                      node: _focusScopeNode,
569
                      child: widget.child,
570 571 572 573 574 575 576
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
577 578
      );
    }
579
  }
580 581
  @override
  Widget build(BuildContext context) {
582
    assert(debugCheckHasMaterialLocalizations(context));
583
    return ListTileTheme(
584 585 586 587
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
588
}