drawer.dart 19 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 6
// @dart = 2.8

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
import 'theme.dart';
17

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

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

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

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

51 52
/// A material design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
53
///
54 55
/// {@youtube 560 315 https://www.youtube.com/watch?v=WRj86iHihgY}
///
56 57
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
58 59 60 61
/// that displays status information about the current user. The remaining
/// drawer children are often constructed with [ListTile]s, often concluding
/// with an [AboutListTile].
///
62 63 64 65 66 67
/// 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}
///
68
/// {@tool snippet}
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 111 112 113 114
/// 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}
///
115 116 117 118
/// An open drawer can be closed by calling [Navigator.pop]. For example
/// a drawer item might close the drawer when tapped:
///
/// ```dart
119 120 121
/// ListTile(
///   leading: Icon(Icons.change_history),
///   title: Text('Change history'),
122 123 124 125 126 127
///   onTap: () {
///     // change app state...
///     Navigator.pop(context); // close the drawer
///   },
/// );
/// ```
128
///
129
/// See also:
130
///
131 132 133 134 135
///  * [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.
136
///  * <https://material.io/design/components/navigation-drawer.html>
137
class Drawer extends StatelessWidget {
138 139 140
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
141 142
  ///
  /// The [elevation] must be non-negative.
143
  const Drawer({
144
    Key key,
145
    this.elevation = 16.0,
146
    this.child,
147
    this.semanticLabel,
148 149
  }) : assert(elevation != null && elevation >= 0.0),
       super(key: key);
150

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

  /// The widget below this widget in the tree.
160
  ///
161
  /// Typically a [SliverList].
162 163
  ///
  /// {@macro flutter.widgets.child}
164
  final Widget child;
165

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

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

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

213 214
/// Provides interactive behavior for [Drawer] widgets.
///
215 216 217
/// Rarely used directly. Drawer controllers are typically created automatically
/// by [Scaffold] widgets.
///
Ian Hickson's avatar
Ian Hickson committed
218
/// The drawer controller provides the ability to open and close a drawer, either
219 220 221
/// 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.
222 223
///
/// See also:
224
///
225 226
///  * [Drawer], a container with the default width of a drawer.
///  * [Scaffold.drawer], the [Scaffold] slot for showing a drawer.
227
class DrawerController extends StatefulWidget {
228 229 230 231 232
  /// Creates a controller for a [Drawer].
  ///
  /// Rarely used directly.
  ///
  /// The [child] argument must not be null and is typically a [Drawer].
233
  const DrawerController({
234
    GlobalKey key,
235
    @required this.child,
236
    @required this.alignment,
jslavitz's avatar
jslavitz committed
237
    this.drawerCallback,
238
    this.dragStartBehavior = DragStartBehavior.start,
239
    this.scrimColor,
240
    this.edgeDragWidth,
241
    this.enableOpenDragGesture = true,
242
  }) : assert(child != null),
243
       assert(dragStartBehavior != null),
244
       assert(alignment != null),
245
       super(key: key);
246

247
  /// The widget below this widget in the tree.
248 249
  ///
  /// Typically a [Drawer].
250 251
  final Widget child;

252
  /// The alignment of the [Drawer].
253
  ///
254 255
  /// This controls the direction in which the user should swipe to open and
  /// close the drawer.
256 257
  final DrawerAlignment alignment;

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

261 262 263 264 265 266 267 268 269 270 271 272
  /// {@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.
  ///
273
  /// By default, the drag start behavior is [DragStartBehavior.start].
274 275 276
  ///
  /// See also:
  ///
277 278 279
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
280 281 282
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

283 284
  /// The color to use for the scrim that obscures primary content while a drawer is open.
  ///
285
  /// By default, the color used is [Colors.black54]
286 287
  final Color scrimColor;

288 289 290 291 292
  /// Determines if the [Drawer] can be opened with a drag gesture.
  ///
  /// By default, the drag gesture is enabled.
  final bool enableOpenDragGesture;

293 294 295 296 297 298 299 300 301 302 303
  /// 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;

304
  @override
305
  DrawerControllerState createState() => DrawerControllerState();
306
}
307

308 309 310
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
311
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
312
  @override
313 314
  void initState() {
    super.initState();
315
    _scrimColorTween = _buildScrimColorTween();
316
    _controller = AnimationController(duration: _kBaseSettleDuration, vsync: this)
317 318
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
319 320
  }

321
  @override
322
  void dispose() {
323
    _historyEntry?.remove();
324
    _controller.dispose();
325 326 327
    super.dispose();
  }

328 329 330 331 332 333 334
  @override
  void didUpdateWidget(DrawerController oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.scrimColor != oldWidget.scrimColor)
      _scrimColorTween = _buildScrimColorTween();
  }

335
  void _animationChanged() {
336
    setState(() {
337
      // The animation controller's state is our build state, and it changed already.
338 339 340
    });
  }

341
  LocalHistoryEntry _historyEntry;
342
  final FocusScopeNode _focusScopeNode = FocusScopeNode();
343 344 345

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
346
      final ModalRoute<dynamic> route = ModalRoute.of(context);
347
      if (route != null) {
348
        _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
349
        route.addLocalHistoryEntry(_historyEntry);
350
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
351 352 353 354
      }
    }
  }

355
  void _animationStatusChanged(AnimationStatus status) {
356
    switch (status) {
357
      case AnimationStatus.forward:
358 359
        _ensureHistoryEntry();
        break;
360
      case AnimationStatus.reverse:
361 362 363
        _historyEntry?.remove();
        _historyEntry = null;
        break;
364
      case AnimationStatus.dismissed:
365
        break;
366
      case AnimationStatus.completed:
367 368
        break;
    }
369 370
  }

371 372 373 374
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
375

376
  AnimationController _controller;
Hixie's avatar
Hixie committed
377

378
  void _handleDragDown(DragDownDetails details) {
379
    _controller.stop();
380
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
381 382
  }

383 384 385 386 387 388 389 390 391 392
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

393
  final GlobalKey _drawerKey = GlobalKey();
394

Hixie's avatar
Hixie committed
395
  double get _width {
396
    final RenderBox box = _drawerKey.currentContext?.findRenderObject() as RenderBox;
397 398
    if (box != null)
      return box.size.width;
Hixie's avatar
Hixie committed
399 400 401
    return _kWidth; // drawer not being shown currently
  }

jslavitz's avatar
jslavitz committed
402 403
  bool _previouslyOpened = false;

404
  void _move(DragUpdateDetails details) {
405 406 407 408 409 410 411 412
    double delta = details.primaryDelta / _width;
    switch (widget.alignment) {
      case DrawerAlignment.start:
        break;
      case DrawerAlignment.end:
        delta = -delta;
        break;
    }
413 414 415 416 417 418 419 420
    switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.value -= delta;
        break;
      case TextDirection.ltr:
        _controller.value += delta;
        break;
    }
jslavitz's avatar
jslavitz committed
421

422
    final bool opened = _controller.value > 0.5;
jslavitz's avatar
jslavitz committed
423 424 425
    if (opened != _previouslyOpened && widget.drawerCallback != null)
      widget.drawerCallback(opened);
    _previouslyOpened = opened;
426 427
  }

428
  void _settle(DragEndDetails details) {
429
    if (_controller.isDismissed)
430
      return;
431
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
432 433 434 435 436 437 438 439
      double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
      switch (widget.alignment) {
        case DrawerAlignment.start:
          break;
        case DrawerAlignment.end:
          visualVelocity = -visualVelocity;
          break;
      }
440
      switch (Directionality.of(context)) {
441 442
        case TextDirection.rtl:
          _controller.fling(velocity: -visualVelocity);
443 444
          if (widget.drawerCallback != null)
            widget.drawerCallback(visualVelocity < 0.0);
445 446 447
          break;
        case TextDirection.ltr:
          _controller.fling(velocity: visualVelocity);
448 449
          if (widget.drawerCallback != null)
            widget.drawerCallback(visualVelocity > 0.0);
450
          break;
451
      }
452
    } else if (_controller.value < 0.5) {
453
      close();
454
    } else {
455
      open();
456 457 458
    }
  }

459 460
  /// Starts an animation to open the drawer.
  ///
461
  /// Typically called by [ScaffoldState.openDrawer].
462
  void open() {
463
    _controller.fling(velocity: 1.0);
jslavitz's avatar
jslavitz committed
464 465
    if (widget.drawerCallback != null)
      widget.drawerCallback(true);
466 467
  }

468
  /// Starts an animation to close the drawer.
469
  void close() {
470
    _controller.fling(velocity: -1.0);
jslavitz's avatar
jslavitz committed
471 472
    if (widget.drawerCallback != null)
      widget.drawerCallback(false);
473
  }
474

475
  ColorTween _scrimColorTween;
476
  final GlobalKey _gestureDetectorKey = GlobalKey();
477

478 479 480 481
  ColorTween _buildScrimColorTween() {
    return ColorTween(begin: Colors.transparent, end: widget.scrimColor ?? Colors.black54);
  }

482
  AlignmentDirectional get _drawerOuterAlignment {
483
    assert(widget.alignment != null);
484 485 486 487 488 489
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerStart;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerEnd;
    }
490
    return null;
491 492 493
  }

  AlignmentDirectional get _drawerInnerAlignment {
494
    assert(widget.alignment != null);
495 496 497 498 499 500
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerEnd;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerStart;
    }
501
    return null;
502 503
  }

504
  Widget _buildDrawer(BuildContext context) {
505 506
    final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
    final EdgeInsets padding = MediaQuery.of(context).padding;
507 508 509 510 511
    final TextDirection textDirection = Directionality.of(context);

    double dragAreaWidth = widget.edgeDragWidth;
    if (widget.edgeDragWidth == null) {
      switch (textDirection) {
512
        case TextDirection.ltr:
513 514
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.left : padding.right);
515 516
          break;
        case TextDirection.rtl:
517 518
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.right : padding.left);
519
          break;
520 521
      }
    }
522

523
    if (_controller.status == AnimationStatus.dismissed) {
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
      if (widget.enableOpenDragGesture) {
        return Align(
          alignment: _drawerOuterAlignment,
          child: GestureDetector(
            key: _gestureDetectorKey,
            onHorizontalDragUpdate: _move,
            onHorizontalDragEnd: _settle,
            behavior: HitTestBehavior.translucent,
            excludeFromSemantics: true,
            dragStartBehavior: widget.dragStartBehavior,
            child: Container(width: dragAreaWidth),
          ),
        );
      } else {
        return const SizedBox.shrink();
      }
540
    } else {
541 542 543 544 545 546
      bool platformHasBackButton;
      switch (Theme.of(context).platform) {
        case TargetPlatform.android:
          platformHasBackButton = true;
          break;
        case TargetPlatform.iOS:
547
        case TargetPlatform.macOS:
548
        case TargetPlatform.fuchsia:
549 550
        case TargetPlatform.linux:
        case TargetPlatform.windows:
551 552 553 554
          platformHasBackButton = false;
          break;
      }
      assert(platformHasBackButton != null);
555
      return GestureDetector(
556
        key: _gestureDetectorKey,
557
        onHorizontalDragDown: _handleDragDown,
558 559
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
560
        onHorizontalDragCancel: _handleDragCancel,
561
        excludeFromSemantics: true,
562
        dragStartBehavior: widget.dragStartBehavior,
563 564
        child: RepaintBoundary(
          child: Stack(
565
            children: <Widget>[
566
              BlockSemantics(
567
                child: ExcludeSemantics(
568
                  // On Android, the back button is used to dismiss a modal.
569 570 571 572 573 574 575 576 577 578
                  excluding: platformHasBackButton,
                  child: GestureDetector(
                    onTap: close,
                    child: Semantics(
                      label: MaterialLocalizations.of(context)?.modalBarrierDismissLabel,
                      child: MouseRegion(
                        opaque: true,
                        child: Container( // The drawer's "scrim"
                          color: _scrimColorTween.evaluate(_controller),
                        ),
579
                      ),
580
                    ),
581
                  ),
582
                ),
583
              ),
584
              Align(
585
                alignment: _drawerOuterAlignment,
586
                child: Align(
587
                  alignment: _drawerInnerAlignment,
588
                  widthFactor: _controller.value,
589 590
                  child: RepaintBoundary(
                    child: FocusScope(
591
                      key: _drawerKey,
592
                      node: _focusScopeNode,
593
                      child: widget.child,
594 595 596 597 598 599 600
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
601 602
      );
    }
603
  }
Ian Hickson's avatar
Ian Hickson committed
604

605 606
  @override
  Widget build(BuildContext context) {
607
    assert(debugCheckHasMaterialLocalizations(context));
608
    return ListTileTheme(
609 610 611 612
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
613
}