drawer.dart 19.5 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/gestures.dart' show DragStartBehavior;
6
import 'package:flutter/widgets.dart';
7

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

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

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

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

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

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

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

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

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

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

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

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

244
  /// The widget below this widget in the tree.
245 246
  ///
  /// Typically a [Drawer].
247 248
  final Widget child;

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

jslavitz's avatar
jslavitz committed
255
  /// Optional callback that is called when a [Drawer] is opened or closed.
256
  final DrawerCallback? drawerCallback;
jslavitz's avatar
jslavitz committed
257

258
  /// {@template flutter.material.DrawerController.dragStartBehavior}
259 260 261
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], the drag behavior used for opening
262 263 264
  /// and closing a drawer will begin at the position where the drag gesture won
  /// the arena. If set to [DragStartBehavior.down] it will begin at the position
  /// where a down event is first detected.
265 266 267 268 269
  ///
  /// 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.
  ///
270
  /// By default, the drag start behavior is [DragStartBehavior.start].
271 272 273
  ///
  /// See also:
  ///
274 275 276
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
277 278 279
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

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

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

290 291 292 293 294 295 296 297 298
  /// 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`.
299
  final double? edgeDragWidth;
300

301 302 303 304 305 306 307 308
  /// Whether or not the drawer is opened or closed.
  ///
  /// This parameter is primarily used by the state restoration framework
  /// to restore the drawer's animation controller to the open or closed state
  /// depending on what was last saved to the target platform before the
  /// application was killed.
  final bool isDrawerOpen;

309
  @override
310
  DrawerControllerState createState() => DrawerControllerState();
311
}
312

313 314 315
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
316
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
317
  @override
318 319
  void initState() {
    super.initState();
320
    _scrimColorTween = _buildScrimColorTween();
321 322 323 324 325 326
    _controller = AnimationController(
      value: widget.isDrawerOpen ? 1.0 : 0.0,
      duration: _kBaseSettleDuration,
      vsync: this,
    );
    _controller
327 328
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
329 330
  }

331
  @override
332
  void dispose() {
333
    _historyEntry?.remove();
334
    _controller.dispose();
335 336 337
    super.dispose();
  }

338 339 340 341 342
  @override
  void didUpdateWidget(DrawerController oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.scrimColor != oldWidget.scrimColor)
      _scrimColorTween = _buildScrimColorTween();
343 344 345 346 347 348 349 350 351 352
    if (widget.isDrawerOpen != oldWidget.isDrawerOpen) {
      switch(_controller.status) {
        case AnimationStatus.completed:
        case AnimationStatus.dismissed:
          _controller.value = widget.isDrawerOpen ? 1.0 : 0.0;
          break;
        default:
          break;
      }
    }
353 354
  }

355
  void _animationChanged() {
356
    setState(() {
357
      // The animation controller's state is our build state, and it changed already.
358 359 360
    });
  }

361
  LocalHistoryEntry? _historyEntry;
362
  final FocusScopeNode _focusScopeNode = FocusScopeNode();
363 364 365

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
366
      final ModalRoute<dynamic>? route = ModalRoute.of(context);
367
      if (route != null) {
368
        _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
369
        route.addLocalHistoryEntry(_historyEntry!);
370
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
371 372 373 374
      }
    }
  }

375
  void _animationStatusChanged(AnimationStatus status) {
376
    switch (status) {
377
      case AnimationStatus.forward:
378 379
        _ensureHistoryEntry();
        break;
380
      case AnimationStatus.reverse:
381 382 383
        _historyEntry?.remove();
        _historyEntry = null;
        break;
384
      case AnimationStatus.dismissed:
385
        break;
386
      case AnimationStatus.completed:
387 388
        break;
    }
389 390
  }

391 392 393 394
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
395

396
  late AnimationController _controller;
Hixie's avatar
Hixie committed
397

398
  void _handleDragDown(DragDownDetails details) {
399
    _controller.stop();
400
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
401 402
  }

403 404 405 406 407 408 409 410 411 412
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

413
  final GlobalKey _drawerKey = GlobalKey();
414

Hixie's avatar
Hixie committed
415
  double get _width {
416
    final RenderBox? box = _drawerKey.currentContext?.findRenderObject() as RenderBox?;
417 418
    if (box != null)
      return box.size.width;
Hixie's avatar
Hixie committed
419 420 421
    return _kWidth; // drawer not being shown currently
  }

jslavitz's avatar
jslavitz committed
422 423
  bool _previouslyOpened = false;

424
  void _move(DragUpdateDetails details) {
425
    double delta = details.primaryDelta! / _width;
426 427 428 429 430 431 432
    switch (widget.alignment) {
      case DrawerAlignment.start:
        break;
      case DrawerAlignment.end:
        delta = -delta;
        break;
    }
433
    switch (Directionality.of(context)) {
434 435 436 437 438 439 440
      case TextDirection.rtl:
        _controller.value -= delta;
        break;
      case TextDirection.ltr:
        _controller.value += delta;
        break;
    }
jslavitz's avatar
jslavitz committed
441

442
    final bool opened = _controller.value > 0.5;
jslavitz's avatar
jslavitz committed
443
    if (opened != _previouslyOpened && widget.drawerCallback != null)
444
      widget.drawerCallback!(opened);
jslavitz's avatar
jslavitz committed
445
    _previouslyOpened = opened;
446 447
  }

448
  void _settle(DragEndDetails details) {
449
    if (_controller.isDismissed)
450
      return;
451
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
452 453 454 455 456 457 458 459
      double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
      switch (widget.alignment) {
        case DrawerAlignment.start:
          break;
        case DrawerAlignment.end:
          visualVelocity = -visualVelocity;
          break;
      }
460
      switch (Directionality.of(context)) {
461 462
        case TextDirection.rtl:
          _controller.fling(velocity: -visualVelocity);
463
          widget.drawerCallback?.call(visualVelocity < 0.0);
464 465 466
          break;
        case TextDirection.ltr:
          _controller.fling(velocity: visualVelocity);
467
          widget.drawerCallback?.call(visualVelocity > 0.0);
468
          break;
469
      }
470
    } else if (_controller.value < 0.5) {
471
      close();
472
    } else {
473
      open();
474 475 476
    }
  }

477 478
  /// Starts an animation to open the drawer.
  ///
479
  /// Typically called by [ScaffoldState.openDrawer].
480
  void open() {
481
    _controller.fling(velocity: 1.0);
482
    widget.drawerCallback?.call(true);
483 484
  }

485
  /// Starts an animation to close the drawer.
486
  void close() {
487
    _controller.fling(velocity: -1.0);
488
    widget.drawerCallback?.call(false);
489
  }
490

491
  late ColorTween _scrimColorTween;
492
  final GlobalKey _gestureDetectorKey = GlobalKey();
493

494 495 496 497
  ColorTween _buildScrimColorTween() {
    return ColorTween(begin: Colors.transparent, end: widget.scrimColor ?? Colors.black54);
  }

498
  AlignmentDirectional get _drawerOuterAlignment {
499
    assert(widget.alignment != null);
500 501 502 503 504 505 506 507 508
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerStart;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerEnd;
    }
  }

  AlignmentDirectional get _drawerInnerAlignment {
509
    assert(widget.alignment != null);
510 511 512 513 514 515 516 517
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerEnd;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerStart;
    }
  }

518
  Widget _buildDrawer(BuildContext context) {
519
    final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
520
    final EdgeInsets padding = MediaQuery.of(context).padding;
521
    final TextDirection textDirection = Directionality.of(context);
522

523
    double? dragAreaWidth = widget.edgeDragWidth;
524
    if (widget.edgeDragWidth == null) {
525
      switch (textDirection) {
526
        case TextDirection.ltr:
527 528
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.left : padding.right);
529 530
          break;
        case TextDirection.rtl:
531 532
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.right : padding.left);
533
          break;
534 535
      }
    }
536

537
    if (_controller.status == AnimationStatus.dismissed) {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
      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();
      }
554
    } else {
555
      final bool platformHasBackButton;
556
      switch (Theme.of(context).platform) {
557 558 559 560
        case TargetPlatform.android:
          platformHasBackButton = true;
          break;
        case TargetPlatform.iOS:
561
        case TargetPlatform.macOS:
562
        case TargetPlatform.fuchsia:
563 564
        case TargetPlatform.linux:
        case TargetPlatform.windows:
565 566 567 568
          platformHasBackButton = false;
          break;
      }
      assert(platformHasBackButton != null);
569
      return GestureDetector(
570
        key: _gestureDetectorKey,
571
        onHorizontalDragDown: _handleDragDown,
572 573
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
574
        onHorizontalDragCancel: _handleDragCancel,
575
        excludeFromSemantics: true,
576
        dragStartBehavior: widget.dragStartBehavior,
577 578
        child: RepaintBoundary(
          child: Stack(
579
            children: <Widget>[
580
              BlockSemantics(
581
                child: ExcludeSemantics(
582
                  // On Android, the back button is used to dismiss a modal.
583 584 585 586
                  excluding: platformHasBackButton,
                  child: GestureDetector(
                    onTap: close,
                    child: Semantics(
587
                      label: MaterialLocalizations.of(context).modalBarrierDismissLabel,
588 589 590 591 592
                      child: MouseRegion(
                        opaque: true,
                        child: Container( // The drawer's "scrim"
                          color: _scrimColorTween.evaluate(_controller),
                        ),
593
                      ),
594
                    ),
595
                  ),
596
                ),
597
              ),
598
              Align(
599
                alignment: _drawerOuterAlignment,
600
                child: Align(
601
                  alignment: _drawerInnerAlignment,
602
                  widthFactor: _controller.value,
603 604
                  child: RepaintBoundary(
                    child: FocusScope(
605
                      key: _drawerKey,
606
                      node: _focusScopeNode,
607
                      child: widget.child,
608 609 610 611 612 613 614
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
615 616
      );
    }
617
  }
Ian Hickson's avatar
Ian Hickson committed
618

619 620
  @override
  Widget build(BuildContext context) {
621
    assert(debugCheckHasMaterialLocalizations(context));
622
    return ListTileTheme(
623 624 625 626
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
627
}