drawer.dart 16.5 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 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].
///
/// An open drawer can be closed by calling [Navigator.pop]. For example
/// a drawer item might close the drawer when tapped:
///
/// ```dart
62 63 64
/// ListTile(
///   leading: Icon(Icons.change_history),
///   title: Text('Change history'),
65 66 67 68 69 70
///   onTap: () {
///     // change app state...
///     Navigator.pop(context); // close the drawer
///   },
/// );
/// ```
71
///
72 73 74
/// 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.
75
///
76
/// See also:
77
///
78 79 80 81 82
///  * [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.
83
///  * <https://material.io/design/components/navigation-drawer.html>
84
class Drawer extends StatelessWidget {
85 86 87
  /// Creates a material design drawer.
  ///
  /// Typically used in the [Scaffold.drawer] property.
88 89
  ///
  /// The [elevation] must be non-negative.
90
  const Drawer({
91
    Key key,
92
    this.elevation = 16.0,
93
    this.child,
94
    this.semanticLabel,
95 96
  }) : assert(elevation != null && elevation >= 0.0),
       super(key: key);
97

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

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

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

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

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

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

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

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

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

204 205 206 207 208 209 210 211 212 213 214 215
  /// {@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.
  ///
216
  /// By default, the drag start behavior is [DragStartBehavior.start].
217 218 219
  ///
  /// See also:
  ///
220 221 222
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
223 224 225
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

226 227
  /// The color to use for the scrim that obscures primary content while a drawer is open.
  ///
228
  /// By default, the color used is [Colors.black54]
229 230
  final Color scrimColor;

231 232 233 234 235 236 237 238 239 240 241
  /// 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;

242
  @override
243
  DrawerControllerState createState() => DrawerControllerState();
244
}
245

246 247 248
/// State for a [DrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
249
class DrawerControllerState extends State<DrawerController> with SingleTickerProviderStateMixin {
250
  @override
251 252
  void initState() {
    super.initState();
253
    _scrimColorTween = _buildScrimColorTween();
254
    _controller = AnimationController(duration: _kBaseSettleDuration, vsync: this)
255 256
      ..addListener(_animationChanged)
      ..addStatusListener(_animationStatusChanged);
257 258
  }

259
  @override
260
  void dispose() {
261
    _historyEntry?.remove();
262
    _controller.dispose();
263 264 265
    super.dispose();
  }

266 267 268 269 270 271 272
  @override
  void didUpdateWidget(DrawerController oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.scrimColor != oldWidget.scrimColor)
      _scrimColorTween = _buildScrimColorTween();
  }

273
  void _animationChanged() {
274
    setState(() {
275
      // The animation controller's state is our build state, and it changed already.
276 277 278
    });
  }

279
  LocalHistoryEntry _historyEntry;
280
  final FocusScopeNode _focusScopeNode = FocusScopeNode();
281 282 283

  void _ensureHistoryEntry() {
    if (_historyEntry == null) {
284
      final ModalRoute<dynamic> route = ModalRoute.of(context);
285
      if (route != null) {
286
        _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
287
        route.addLocalHistoryEntry(_historyEntry);
288
        FocusScope.of(context).setFirstFocus(_focusScopeNode);
289 290 291 292
      }
    }
  }

293
  void _animationStatusChanged(AnimationStatus status) {
294
    switch (status) {
295
      case AnimationStatus.forward:
296 297
        _ensureHistoryEntry();
        break;
298
      case AnimationStatus.reverse:
299 300 301
        _historyEntry?.remove();
        _historyEntry = null;
        break;
302
      case AnimationStatus.dismissed:
303
        break;
304
      case AnimationStatus.completed:
305 306
        break;
    }
307 308
  }

309 310 311 312
  void _handleHistoryEntryRemoved() {
    _historyEntry = null;
    close();
  }
313

314
  AnimationController _controller;
Hixie's avatar
Hixie committed
315

316
  void _handleDragDown(DragDownDetails details) {
317
    _controller.stop();
318
    _ensureHistoryEntry();
Hixie's avatar
Hixie committed
319 320
  }

321 322 323 324 325 326 327 328 329 330
  void _handleDragCancel() {
    if (_controller.isDismissed || _controller.isAnimating)
      return;
    if (_controller.value < 0.5) {
      close();
    } else {
      open();
    }
  }

331
  final GlobalKey _drawerKey = GlobalKey();
332

Hixie's avatar
Hixie committed
333
  double get _width {
334 335 336
    final RenderBox box = _drawerKey.currentContext?.findRenderObject();
    if (box != null)
      return box.size.width;
Hixie's avatar
Hixie committed
337 338 339
    return _kWidth; // drawer not being shown currently
  }

jslavitz's avatar
jslavitz committed
340 341
  bool _previouslyOpened = false;

342
  void _move(DragUpdateDetails details) {
343 344 345 346 347 348 349 350
    double delta = details.primaryDelta / _width;
    switch (widget.alignment) {
      case DrawerAlignment.start:
        break;
      case DrawerAlignment.end:
        delta = -delta;
        break;
    }
351 352 353 354 355 356 357 358
    switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.value -= delta;
        break;
      case TextDirection.ltr:
        _controller.value += delta;
        break;
    }
jslavitz's avatar
jslavitz committed
359

360
    final bool opened = _controller.value > 0.5;
jslavitz's avatar
jslavitz committed
361 362 363
    if (opened != _previouslyOpened && widget.drawerCallback != null)
      widget.drawerCallback(opened);
    _previouslyOpened = opened;
364 365
  }

366
  void _settle(DragEndDetails details) {
367
    if (_controller.isDismissed)
368
      return;
369
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
370 371 372 373 374 375 376 377
      double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
      switch (widget.alignment) {
        case DrawerAlignment.start:
          break;
        case DrawerAlignment.end:
          visualVelocity = -visualVelocity;
          break;
      }
378 379 380 381 382 383 384
      switch (Directionality.of(context)) {
      case TextDirection.rtl:
        _controller.fling(velocity: -visualVelocity);
        break;
      case TextDirection.ltr:
        _controller.fling(velocity: visualVelocity);
        break;
385
      }
386
    } else if (_controller.value < 0.5) {
387
      close();
388
    } else {
389
      open();
390 391 392
    }
  }

393 394
  /// Starts an animation to open the drawer.
  ///
395
  /// Typically called by [ScaffoldState.openDrawer].
396
  void open() {
397
    _controller.fling(velocity: 1.0);
jslavitz's avatar
jslavitz committed
398 399
    if (widget.drawerCallback != null)
      widget.drawerCallback(true);
400 401
  }

402
  /// Starts an animation to close the drawer.
403
  void close() {
404
    _controller.fling(velocity: -1.0);
jslavitz's avatar
jslavitz committed
405 406
    if (widget.drawerCallback != null)
      widget.drawerCallback(false);
407
  }
408

409
  ColorTween _scrimColorTween;
410
  final GlobalKey _gestureDetectorKey = GlobalKey();
411

412 413 414 415
  ColorTween _buildScrimColorTween() {
    return ColorTween(begin: Colors.transparent, end: widget.scrimColor ?? Colors.black54);
  }

416
  AlignmentDirectional get _drawerOuterAlignment {
417
    assert(widget.alignment != null);
418 419 420 421 422 423
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerStart;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerEnd;
    }
424
    return null;
425 426 427
  }

  AlignmentDirectional get _drawerInnerAlignment {
428
    assert(widget.alignment != null);
429 430 431 432 433 434
    switch (widget.alignment) {
      case DrawerAlignment.start:
        return AlignmentDirectional.centerEnd;
      case DrawerAlignment.end:
        return AlignmentDirectional.centerStart;
    }
435
    return null;
436 437
  }

438
  Widget _buildDrawer(BuildContext context) {
439 440
    final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
    final EdgeInsets padding = MediaQuery.of(context).padding;
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    final TextDirection textDirection = Directionality.of(context);

    double dragAreaWidth = widget.edgeDragWidth;
    if (widget.edgeDragWidth == null) {
      switch (textDirection) {
        case TextDirection.ltr: {
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.left : padding.right);
        }
        break;
        case TextDirection.rtl: {
          dragAreaWidth = _kEdgeDragWidth +
            (drawerIsStart ? padding.right : padding.left);
        }
        break;
      }
    }
458

459
    if (_controller.status == AnimationStatus.dismissed) {
460
      return Align(
461
        alignment: _drawerOuterAlignment,
462
        child: GestureDetector(
463 464 465 466
          key: _gestureDetectorKey,
          onHorizontalDragUpdate: _move,
          onHorizontalDragEnd: _settle,
          behavior: HitTestBehavior.translucent,
Hixie's avatar
Hixie committed
467
          excludeFromSemantics: true,
468
          dragStartBehavior: widget.dragStartBehavior,
469
          child: Container(width: dragAreaWidth),
470
        ),
471 472
      );
    } else {
473 474 475 476 477 478 479 480 481 482 483
      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);
484
      return GestureDetector(
485
        key: _gestureDetectorKey,
486
        onHorizontalDragDown: _handleDragDown,
487 488
        onHorizontalDragUpdate: _move,
        onHorizontalDragEnd: _settle,
489
        onHorizontalDragCancel: _handleDragCancel,
490
        excludeFromSemantics: true,
491
        dragStartBehavior: widget.dragStartBehavior,
492 493
        child: RepaintBoundary(
          child: Stack(
494
            children: <Widget>[
495 496
              BlockSemantics(
                child: GestureDetector(
497
                  // On Android, the back button is used to dismiss a modal.
498
                  excludeFromSemantics: platformHasBackButton,
499
                  onTap: close,
500
                  child: Semantics(
501
                    label: MaterialLocalizations.of(context)?.modalBarrierDismissLabel,
502 503
                    child: Container( // The drawer's "scrim"
                      color: _scrimColorTween.evaluate(_controller),
504
                    ),
505
                  ),
506
                ),
507
              ),
508
              Align(
509
                alignment: _drawerOuterAlignment,
510
                child: Align(
511
                  alignment: _drawerInnerAlignment,
512
                  widthFactor: _controller.value,
513 514
                  child: RepaintBoundary(
                    child: FocusScope(
515
                      key: _drawerKey,
516
                      node: _focusScopeNode,
517
                      child: widget.child,
518 519 520 521 522 523 524
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
525 526
      );
    }
527
  }
528 529
  @override
  Widget build(BuildContext context) {
530
    assert(debugCheckHasMaterialLocalizations(context));
531
    return ListTileTheme(
532 533 534 535
      style: ListTileStyle.drawer,
      child: _buildDrawer(context),
    );
  }
536
}