drawer.dart 18 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/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 180 181 182 183 184 185
      case TargetPlatform.iOS:
        label = semanticLabel;
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        label = semanticLabel ?? MaterialLocalizations.of(context)?.drawerLabel;
    }
186
    return Semantics(
187 188 189 190
      scopesRoute: true,
      namesRoute: true,
      explicitChildNodes: true,
      label: label,
191
      child: ConstrainedBox(
192
        constraints: const BoxConstraints.expand(width: _kWidth),
193
        child: Material(
194 195 196
          elevation: elevation,
          child: child,
        ),
197
      ),
198 199 200 201
    );
  }
}

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

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

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

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

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

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

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

280 281 282 283 284 285 286 287 288 289 290
  /// 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;

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

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

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

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

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

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

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

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

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

363
  AnimationController _controller;
Hixie's avatar
Hixie committed
364

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

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

380
  final GlobalKey _drawerKey = GlobalKey();
381

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

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

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

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

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

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

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

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

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

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

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

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

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

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