dropdown.dart 35.7 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 'dart:math' as math;
6 7 8

import 'package:flutter/widgets.dart';

9
import 'button_theme.dart';
10
import 'colors.dart';
11
import 'constants.dart';
12
import 'debug.dart';
13
import 'icons.dart';
14
import 'ink_well.dart';
15
import 'input_decorator.dart';
16
import 'material.dart';
17
import 'material_localizations.dart';
18
import 'scrollbar.dart';
19 20 21
import 'shadows.dart';
import 'theme.dart';

22
const Duration _kDropdownMenuDuration = Duration(milliseconds: 300);
23
const double _kMenuItemHeight = kMinInteractiveDimension;
24
const double _kDenseButtonHeight = 24.0;
25 26
const EdgeInsets _kMenuItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
const EdgeInsetsGeometry _kAlignedButtonPadding = EdgeInsetsDirectional.only(start: 16.0, end: 4.0);
27 28
const EdgeInsets _kUnalignedButtonPadding = EdgeInsets.zero;
const EdgeInsets _kAlignedMenuMargin = EdgeInsets.zero;
29
const EdgeInsetsGeometry _kUnalignedMenuMargin = EdgeInsetsDirectional.only(start: 16.0, end: 24.0);
30

31 32
typedef DropdownButtonBuilder = List<Widget> Function(BuildContext context);

33 34
class _DropdownMenuPainter extends CustomPainter {
  _DropdownMenuPainter({
35 36
    this.color,
    this.elevation,
37
    this.selectedIndex,
38
    this.resize,
39
  }) : _painter = BoxDecoration(
40
         // If you add an image here, you must provide a real
41 42
         // configuration in the paint() function and you must provide some sort
         // of onChanged callback here.
43
         color: color,
44
         borderRadius: BorderRadius.circular(2.0),
45
         boxShadow: kElevationToShadow[elevation],
46 47
       ).createBoxPainter(),
       super(repaint: resize);
48 49 50

  final Color color;
  final int elevation;
51 52 53 54
  final int selectedIndex;
  final Animation<double> resize;

  final BoxPainter _painter;
55

56
  @override
57
  void paint(Canvas canvas, Size size) {
58
    final double selectedItemOffset = selectedIndex * _kMenuItemHeight + kMaterialListPadding.top;
59
    final Tween<double> top = Tween<double>(
60
      begin: selectedItemOffset.clamp(0.0, size.height - _kMenuItemHeight),
61
      end: 0.0,
62 63
    );

64
    final Tween<double> bottom = Tween<double>(
65
      begin: (top.begin + _kMenuItemHeight).clamp(_kMenuItemHeight, size.height),
66
      end: size.height,
67 68
    );

69
    final Rect rect = Rect.fromLTRB(0.0, top.evaluate(resize), size.width, bottom.evaluate(resize));
70

71
    _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
72 73
  }

74
  @override
75
  bool shouldRepaint(_DropdownMenuPainter oldPainter) {
76 77
    return oldPainter.color != color
        || oldPainter.elevation != elevation
78 79
        || oldPainter.selectedIndex != selectedIndex
        || oldPainter.resize != resize;
80 81 82
  }
}

83 84
// Do not use the platform-specific default scroll configuration.
// Dropdown menus should never overscroll or display an overscroll indicator.
Adam Barth's avatar
Adam Barth committed
85
class _DropdownScrollBehavior extends ScrollBehavior {
86
  const _DropdownScrollBehavior();
87 88

  @override
89
  TargetPlatform getPlatform(BuildContext context) => Theme.of(context).platform;
90 91

  @override
92
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) => child;
93 94

  @override
95
  ScrollPhysics getScrollPhysics(BuildContext context) => const ClampingScrollPhysics();
96 97
}

98
class _DropdownMenu<T> extends StatefulWidget {
99
  const _DropdownMenu({
100
    Key key,
101
    this.padding,
102 103
    this.route,
  }) : super(key: key);
104

105
  final _DropdownRoute<T> route;
106
  final EdgeInsets padding;
107

108
  @override
109
  _DropdownMenuState<T> createState() => _DropdownMenuState<T>();
110 111
}

112
class _DropdownMenuState<T> extends State<_DropdownMenu<T>> {
113 114 115 116 117 118 119 120 121 122
  CurvedAnimation _fadeOpacity;
  CurvedAnimation _resize;

  @override
  void initState() {
    super.initState();
    // We need to hold these animations as state because of their curve
    // direction. When the route's animation reverses, if we were to recreate
    // the CurvedAnimation objects in build, we'd lose
    // CurvedAnimation._curveDirection.
123
    _fadeOpacity = CurvedAnimation(
124
      parent: widget.route.animation,
125
      curve: const Interval(0.0, 0.25),
126
      reverseCurve: const Interval(0.75, 1.0),
127
    );
128
    _resize = CurvedAnimation(
129
      parent: widget.route.animation,
130
      curve: const Interval(0.25, 0.5),
131
      reverseCurve: const Threshold(0.0),
132 133 134
    );
  }

135
  @override
136 137
  Widget build(BuildContext context) {
    // The menu is shown in three stages (unit timing in brackets):
Hixie's avatar
Hixie committed
138 139
    // [0s - 0.25s] - Fade in a rect-sized menu container with the selected item.
    // [0.25s - 0.5s] - Grow the otherwise empty menu container from the center
140
    //   until it's big enough for as many items as we're going to show.
Hixie's avatar
Hixie committed
141
    // [0.5s - 1.0s] Fade in the remaining visible items from top to bottom.
142 143
    //
    // When the menu is dismissed we just fade the entire thing out
Hixie's avatar
Hixie committed
144
    // in the first 0.25s.
145
    assert(debugCheckHasMaterialLocalizations(context));
146
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
147
    final _DropdownRoute<T> route = widget.route;
Adam Barth's avatar
Adam Barth committed
148
    final double unit = 0.5 / (route.items.length + 1.5);
149
    final List<Widget> children = <Widget>[];
Adam Barth's avatar
Adam Barth committed
150
    for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex) {
151
      CurvedAnimation opacity;
Adam Barth's avatar
Adam Barth committed
152
      if (itemIndex == route.selectedIndex) {
153
        opacity = CurvedAnimation(parent: route.animation, curve: const Threshold(0.0));
154 155 156
      } else {
        final double start = (0.5 + (itemIndex + 1) * unit).clamp(0.0, 1.0);
        final double end = (start + 1.5 * unit).clamp(0.0, 1.0);
157
        opacity = CurvedAnimation(parent: route.animation, curve: Interval(start, end));
158
      }
159
      children.add(FadeTransition(
160
        opacity: opacity,
161 162
        child: InkWell(
          child: Container(
163
            padding: widget.padding,
164
            child: route.items[itemIndex],
165
          ),
166 167
          onTap: () => Navigator.pop(
            context,
168
            _DropdownRouteResult<T>(route.items[itemIndex].value),
169 170
          ),
        ),
171 172 173
      ));
    }

174
    return FadeTransition(
175
      opacity: _fadeOpacity,
176 177
      child: CustomPaint(
        painter: _DropdownMenuPainter(
178 179 180
          color: Theme.of(context).canvasColor,
          elevation: route.elevation,
          selectedIndex: route.selectedIndex,
181
          resize: _resize,
182
        ),
183
        child: Semantics(
184 185 186 187
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
188
          child: Material(
189 190 191 192 193 194 195 196 197 198 199
            type: MaterialType.transparency,
            textStyle: route.style,
            child: ScrollConfiguration(
              behavior: const _DropdownScrollBehavior(),
              child: Scrollbar(
                child: ListView(
                  controller: widget.route.scrollController,
                  padding: kMaterialListPadding,
                  itemExtent: _kMenuItemHeight,
                  shrinkWrap: true,
                  children: children,
200
                ),
201 202 203 204
              ),
            ),
          ),
        ),
205 206
      ),
    );
207 208 209
  }
}

210
class _DropdownMenuRouteLayout<T> extends SingleChildLayoutDelegate {
211 212 213 214 215 216
  _DropdownMenuRouteLayout({
    @required this.buttonRect,
    @required this.menuTop,
    @required this.menuHeight,
    @required this.textDirection,
  });
217

218 219 220
  final Rect buttonRect;
  final double menuTop;
  final double menuHeight;
221
  final TextDirection textDirection;
222 223 224

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
225 226 227
    // The maximum height of a simple menu should be one or more rows less than
    // the view height. This ensures a tappable area outside of the simple menu
    // with which to dismiss the menu.
228
    //   -- https://material.io/design/components/menus.html#usage
229
    final double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight);
230 231
    // The width of a menu should be at most the view width. This ensures that
    // the menu does not extend past the left and right edges of the screen.
232
    final double width = math.min(constraints.maxWidth, buttonRect.width);
233
    return BoxConstraints(
234 235
      minWidth: width,
      maxWidth: width,
236
      minHeight: 0.0,
237
      maxHeight: maxHeight,
238 239 240 241 242
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
243
    assert(() {
244
      final Rect container = Offset.zero & size;
245 246 247 248
      if (container.intersect(buttonRect) == buttonRect) {
        // If the button was entirely on-screen, then verify
        // that the menu is also on-screen.
        // If the button was a bit off-screen, then, oh well.
249 250
        assert(menuTop >= 0.0);
        assert(menuTop + menuHeight <= size.height);
251 252
      }
      return true;
253
    }());
254 255 256 257
    assert(textDirection != null);
    double left;
    switch (textDirection) {
      case TextDirection.rtl:
258
        left = buttonRect.right.clamp(0.0, size.width) - childSize.width;
259 260 261 262 263
        break;
      case TextDirection.ltr:
        left = buttonRect.left.clamp(0.0, size.width - childSize.width);
        break;
    }
264
    return Offset(left, menuTop);
265 266 267
  }

  @override
268 269
  bool shouldRelayout(_DropdownMenuRouteLayout<T> oldDelegate) {
    return buttonRect != oldDelegate.buttonRect
270 271 272
        || menuTop != oldDelegate.menuTop
        || menuHeight != oldDelegate.menuHeight
        || textDirection != oldDelegate.textDirection;
273
  }
274 275
}

276 277 278
// We box the return value so that the return value can be null. Otherwise,
// canceling the route (which returns null) would get confused with actually
// returning a real null value.
279 280
class _DropdownRouteResult<T> {
  const _DropdownRouteResult(this.result);
281

282
  final T result;
283 284

  @override
285
  bool operator ==(dynamic other) {
286
    if (other is! _DropdownRouteResult<T>)
287
      return false;
288
    final _DropdownRouteResult<T> typedOther = other;
289 290
    return result == typedOther.result;
  }
291 292

  @override
293 294 295
  int get hashCode => result.hashCode;
}

296 297
class _DropdownRoute<T> extends PopupRoute<_DropdownRouteResult<T>> {
  _DropdownRoute({
298
    this.items,
299
    this.padding,
300
    this.buttonRect,
301
    this.selectedIndex,
302
    this.elevation = 8,
303
    this.theme,
304
    @required this.style,
305
    this.barrierLabel,
306
  }) : assert(style != null);
307

308
  final List<DropdownMenuItem<T>> items;
309
  final EdgeInsetsGeometry padding;
310
  final Rect buttonRect;
Hixie's avatar
Hixie committed
311
  final int selectedIndex;
Hans Muller's avatar
Hans Muller committed
312
  final int elevation;
313
  final ThemeData theme;
314 315
  final TextStyle style;

316
  ScrollController scrollController;
317

318
  @override
319
  Duration get transitionDuration => _kDropdownMenuDuration;
320 321

  @override
322
  bool get barrierDismissible => true;
323 324

  @override
Hixie's avatar
Hixie committed
325
  Color get barrierColor => null;
326

327 328 329
  @override
  final String barrierLabel;

330
  @override
331
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return _DropdownRoutePage<T>(
          route: this,
          constraints: constraints,
          items: items,
          padding: padding,
          buttonRect: buttonRect,
          selectedIndex: selectedIndex,
          elevation: elevation,
          theme: theme,
          style: style,
        );
      }
    );
  }

  void _dismiss() {
    navigator?.removeRoute(this);
  }
}

class _DropdownRoutePage<T> extends StatelessWidget {
355
  const _DropdownRoutePage({
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    Key key,
    this.route,
    this.constraints,
    this.items,
    this.padding,
    this.buttonRect,
    this.selectedIndex,
    this.elevation = 8,
    this.theme,
    this.style,
  }) : super(key: key);

  final _DropdownRoute<T> route;
  final BoxConstraints constraints;
  final List<DropdownMenuItem<T>> items;
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final int selectedIndex;
  final int elevation;
  final ThemeData theme;
  final TextStyle style;

  @override
  Widget build(BuildContext context) {
380
    assert(debugCheckHasDirectionality(context));
381 382
    final double availableHeight = constraints.maxHeight;
    final double maxMenuHeight = availableHeight - 2.0 * _kMenuItemHeight;
383 384

    final double buttonTop = buttonRect.top;
385
    final double buttonBottom = math.min(buttonRect.bottom, availableHeight);
386 387 388 389 390 391

    // If the button is placed on the bottom or top of the screen, its top or
    // bottom may be less than [_kMenuItemHeight] from the edge of the screen.
    // In this case, we want to change the menu limits to align with the top
    // or bottom edge of the button.
    final double topLimit = math.min(_kMenuItemHeight, buttonTop);
392
    final double bottomLimit = math.max(availableHeight - _kMenuItemHeight, buttonBottom);
393

394
    final double selectedItemOffset = selectedIndex * _kMenuItemHeight + kMaterialListPadding.top;
395

396
    double menuTop = (buttonTop - selectedItemOffset) - (_kMenuItemHeight - buttonRect.height) / 2.0;
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    final double preferredMenuHeight = (items.length * _kMenuItemHeight) + kMaterialListPadding.vertical;

    // If there are too many elements in the menu, we need to shrink it down
    // so it is at most the maxMenuHeight.
    final double menuHeight = math.min(maxMenuHeight, preferredMenuHeight);

    double menuBottom = menuTop + menuHeight;

    // If the computed top or bottom of the menu are outside of the range
    // specified, we need to bring them into range. If the item height is larger
    // than the button height and the button is at the very bottom or top of the
    // screen, the menu will be aligned with the bottom or top of the button
    // respectively.
    if (menuTop < topLimit)
      menuTop = math.min(buttonTop, topLimit);
412

413 414 415
    if (menuBottom > bottomLimit) {
      menuBottom = math.max(buttonBottom, bottomLimit);
      menuTop = menuBottom - menuHeight;
416 417
    }

418
    if (route.scrollController == null) {
419 420 421 422 423 424
      // The limit is asymmetrical because we do not care how far positive the
      // limit goes. We are only concerned about the case where the value of
      // [buttonTop - menuTop] is larger than selectedItemOffset, ie. when
      // the button is close to the bottom of the screen and the selected item
      // is close to 0.
      final double scrollOffset = preferredMenuHeight > maxMenuHeight ? math.max(0.0, selectedItemOffset - (buttonTop - menuTop)) : 0.0;
425
      route.scrollController = ScrollController(initialScrollOffset: scrollOffset);
426 427
    }

428
    final TextDirection textDirection = Directionality.of(context);
429
    Widget menu = _DropdownMenu<T>(
430
      route: route,
431 432 433
      padding: padding.resolve(textDirection),
    );

434
    if (theme != null)
435
      menu = Theme(data: theme, child: menu);
436

437
    return MediaQuery.removePadding(
438 439 440 441 442
      context: context,
      removeTop: true,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
443
      child: Builder(
444
        builder: (BuildContext context) {
445 446
          return CustomSingleChildLayout(
            delegate: _DropdownMenuRouteLayout<T>(
447 448 449
              buttonRect: buttonRect,
              menuTop: menuTop,
              menuHeight: menuHeight,
450
              textDirection: textDirection,
451 452 453 454
            ),
            child: menu,
          );
        },
455
      ),
456
    );
457
  }
458 459
}

460
/// An item in a menu created by a [DropdownButton].
461 462 463
///
/// The type `T` is the type of the value the entry represents. All the entries
/// in a given menu must represent values with consistent types.
464
class DropdownMenuItem<T> extends StatelessWidget {
465
  /// Creates an item for a dropdown menu.
466 467
  ///
  /// The [child] argument is required.
468
  const DropdownMenuItem({
469 470
    Key key,
    this.value,
471
    @required this.child,
472 473
  }) : assert(child != null),
       super(key: key);
474

475
  /// The widget below this widget in the tree.
476 477
  ///
  /// Typically a [Text] widget.
478
  final Widget child;
479 480 481

  /// The value to return if the user selects this menu item.
  ///
482
  /// Eventually returned in a call to [DropdownButton.onChanged].
483
  final T value;
484

485
  @override
486
  Widget build(BuildContext context) {
487
    return Container(
488
      height: _kMenuItemHeight,
489
      alignment: AlignmentDirectional.centerStart,
490
      child: child,
491 492 493 494
    );
  }
}

495
/// An inherited widget that causes any descendant [DropdownButton]
496 497 498
/// widgets to not include their regular underline.
///
/// This is used by [DataTable] to remove the underline from any
499
/// [DropdownButton] widgets placed within material data tables, as
500
/// required by the material design specification.
501 502
class DropdownButtonHideUnderline extends InheritedWidget {
  /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must
503
  /// be given.
504
  const DropdownButtonHideUnderline({
505
    Key key,
506
    @required Widget child,
507 508
  }) : assert(child != null),
       super(key: key, child: child);
509

510
  /// Returns whether the underline of [DropdownButton] widgets should
511 512
  /// be hidden.
  static bool at(BuildContext context) {
513
    return context.inheritFromWidgetOfExactType(DropdownButtonHideUnderline) != null;
514 515 516
  }

  @override
517
  bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false;
518 519
}

520 521 522 523 524 525
/// A material design button for selecting from a list of items.
///
/// A dropdown button lets the user select from a number of items. The button
/// shows the currently selected item as well as an arrow that opens a menu for
/// selecting another item.
///
526 527
/// The type `T` is the type of the [value] that each dropdown item represents.
/// All the entries in a given menu must represent values with consistent types.
528 529 530
/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be
/// specialized with that same type argument.
///
531 532 533 534
/// The [onChanged] callback should update a state variable that defines the
/// dropdown's value. It should also call [State.setState] to rebuild the
/// dropdown with the new value.
///
535
/// {@tool snippet --template=stateful_widget_scaffold_center}
536
///
537 538 539 540
/// This sample shows a `DropdownButton` with a customized icon, text style,
/// and underline and whose value is one of "One", "Two", "Free", or "Four".
///
/// ![A screenshot of the dropdown button](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png)
541
///
542
/// ```dart
543 544
/// String dropdownValue = 'One';
///
545
/// @override
546
/// Widget build(BuildContext context) {
547 548 549 550 551 552 553
///   return DropdownButton<String>(
///     value: dropdownValue,
///     icon: Icon(Icons.arrow_downward),
///     iconSize: 24,
///     elevation: 16,
///     style: TextStyle(
///       color: Colors.deepPurple
554
///     ),
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
///     underline: Container(
///       height: 2,
///       color: Colors.deepPurpleAccent,
///     ),
///     onChanged: (String newValue) {
///       setState(() {
///         dropdownValue = newValue;
///       });
///     },
///     items: <String>['One', 'Two', 'Free', 'Four']
///       .map<DropdownMenuItem<String>>((String value) {
///         return DropdownMenuItem<String>(
///           value: value,
///           child: Text(value),
///         );
///       })
///       .toList(),
572 573 574 575 576 577 578 579 580 581
///   );
/// }
/// ```
/// {@end-tool}
///
/// If the [onChanged] callback is null or the list of [items] is null
/// then the dropdown button will be disabled, i.e. its arrow will be
/// displayed in grey and it will not respond to input. A disabled button
/// will display the [disabledHint] widget if it is non-null.
///
582 583 584
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
585
///
586
///  * [DropdownMenuItem], the class used to represent the [items].
587
///  * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons
588 589
///    from displaying their underlines.
///  * [RaisedButton], [FlatButton], ordinary buttons that trigger a single action.
590
///  * <https://material.io/design/components/menus.html#dropdown-menu>
591
class DropdownButton<T> extends StatefulWidget {
592
  /// Creates a dropdown button.
593
  ///
594 595 596 597
  /// The [items] must have distinct values. If [value] isn't null then it
  /// must be equal to one of the [DropDownMenuItem] values. If [items] or
  /// [onChanged] is null, the button will be disabled, the down arrow
  /// will be greyed out, and the [disabledHint] will be shown (if provided).
598 599
  ///
  /// The [elevation] and [iconSize] arguments must not be null (they both have
600 601
  /// defaults, so do not need to be specified). The boolean [isDense] and
  /// [isExpanded] arguments must not be null.
602
  DropdownButton({
603
    Key key,
604
    @required this.items,
605
    this.selectedItemBuilder,
606
    this.value,
607
    this.hint,
608
    this.disabledHint,
609
    @required this.onChanged,
610
    this.elevation = 8,
611
    this.style,
612
    this.underline,
613 614 615
    this.icon,
    this.iconDisabledColor,
    this.iconEnabledColor,
616 617
    this.iconSize = 24.0,
    this.isDense = false,
618
    this.isExpanded = false,
619
  }) : assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1),
620 621 622 623 624
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
       super(key: key);
625

626 627 628 629 630 631
  /// The list of items the user can select.
  ///
  /// If the [onChanged] callback is null or the list of items is null
  /// then the dropdown button will be disabled, i.e. its arrow will be
  /// displayed in grey and it will not respond to input. A disabled button
  /// will display the [disabledHint] widget if it is non-null.
632
  final List<DropdownMenuItem<T>> items;
633

634 635 636
  /// The value of the currently selected [DropdownMenuItem], or null if no
  /// item has been selected. If `value` is null then the menu is popped up as
  /// if the first item were selected.
637
  final T value;
638

639
  /// A placeholder widget that is displayed if no item is selected, i.e. if [value] is null.
640 641
  final Widget hint;

642 643 644 645 646
  /// A message to show when the dropdown is disabled.
  ///
  /// Displayed if [items] or [onChanged] is null.
  final Widget disabledHint;

647
  /// {@template flutter.material.dropdownButton.onChanged}
648
  /// Called when the user selects an item.
649 650 651 652 653
  ///
  /// If the [onChanged] callback is null or the list of [items] is null
  /// then the dropdown button will be disabled, i.e. its arrow will be
  /// displayed in grey and it will not respond to input. A disabled button
  /// will display the [disabledHint] widget if it is non-null.
654
  /// {@endtemplate}
Hixie's avatar
Hixie committed
655
  final ValueChanged<T> onChanged;
656

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
  /// A builder to customize the dropdown buttons corresponding to the
  /// [DropdownMenuItem]s in [items].
  ///
  /// When a [DropdownMenuItem] is selected, the widget that will be displayed
  /// from the list corresponds to the [DropdownMenuItem] of the same index
  /// in [items].
  ///
  /// {@tool snippet --template=stateful_widget_scaffold}
  ///
  /// This sample shows a `DropdownButton` with a button with [Text] that
  /// corresponds to but is unique from [DropdownMenuItem].
  ///
  /// ```dart
  /// final List<String> items = <String>['1','2','3'];
  /// String selectedItem = '1';
  ///
  /// @override
  /// Widget build(BuildContext context) {
  ///   return Padding(
  ///     padding: const EdgeInsets.symmetric(horizontal: 12.0),
  ///     child: DropdownButton<String>(
  ///       value: selectedItem,
  ///       onChanged: (String string) => setState(() => selectedItem = string),
  ///       selectedItemBuilder: (BuildContext context) {
  ///         return items.map((String item) {
  ///           return Text(item);
  ///         }).toList();
  ///       },
  ///       items: items.map((String item) {
  ///         return DropdownMenuItem<String>(
  ///           child: Text('Log $item'),
  ///           value: item,
  ///         );
  ///       }).toList(),
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// If this callback is null, the [DropdownMenuItem] from [items]
  /// that matches [value] will be displayed.
  final DropdownButtonBuilder selectedItemBuilder;

701
  /// The z-coordinate at which to place the menu when open.
702
  ///
703 704
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12,
  /// 16, and 24. See [kElevationToShadow].
705 706
  ///
  /// Defaults to 8, the appropriate elevation for dropdown buttons.
Hans Muller's avatar
Hans Muller committed
707
  final int elevation;
708

709
  /// The text style to use for text in the dropdown button and the dropdown
710 711 712 713 714 715
  /// menu that appears when you tap the button.
  ///
  /// Defaults to the [TextTheme.subhead] value of the current
  /// [ThemeData.textTheme] of the current [Theme].
  final TextStyle style;

716 717 718 719 720
  /// The widget to use for drawing the drop-down button's underline.
  ///
  /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD.
  final Widget underline;

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  /// The widget to use for the drop-down button's icon.
  ///
  /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph.
  final Widget icon;

  /// The color of any [Icon] descendant of [icon] if this button is disabled,
  /// i.e. if [onChanged] is null.
  ///
  /// Defaults to [Colors.grey.shade400] when the theme's
  /// [ThemeData.brightness] is [Brightness.light] and to
  /// [Colors.white10] when it is [Brightness.dark]
  final Color iconDisabledColor;

  /// The color of any [Icon] descendant of [icon] if this button is enabled,
  /// i.e. if [onChanged] is defined.
  ///
  /// Defaults to [Colors.grey.shade700] when the theme's
  /// [ThemeData.brightness] is [Brightness.light] and to
  /// [Colors.white70] when it is [Brightness.dark]
  final Color iconEnabledColor;

742 743
  /// The size to use for the drop-down button's down arrow icon button.
  ///
744
  /// Defaults to 24.0.
745 746
  final double iconSize;

747 748 749 750 751
  /// Reduce the button's height.
  ///
  /// By default this button's height is the same as its menu items' heights.
  /// If isDense is true, the button's height is reduced by about half. This
  /// can be useful when the button is embedded in a container that adds
752
  /// its own decorations, like [InputDecorator].
753 754
  final bool isDense;

755 756 757 758 759 760 761
  /// Set the dropdown's inner contents to horizontally fill its parent.
  ///
  /// By default this button's inner width is the minimum size of its contents.
  /// If [isExpanded] is true, the inner width is expanded to fill its
  /// surrounding container.
  final bool isExpanded;

762
  @override
763
  _DropdownButtonState<T> createState() => _DropdownButtonState<T>();
764 765
}

766
class _DropdownButtonState<T> extends State<DropdownButton<T>> with WidgetsBindingObserver {
767
  int _selectedIndex;
768
  _DropdownRoute<T> _dropdownRoute;
769

770
  @override
771 772 773
  void initState() {
    super.initState();
    _updateSelectedIndex();
774
    WidgetsBinding.instance.addObserver(this);
775 776
  }

777 778 779
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
780
    _removeDropdownRoute();
781 782 783 784 785 786 787
    super.dispose();
  }

  // Typically called because the device's orientation has changed.
  // Defined by WidgetsBindingObserver
  @override
  void didChangeMetrics() {
788 789 790 791 792
    _removeDropdownRoute();
  }

  void _removeDropdownRoute() {
    _dropdownRoute?._dismiss();
793 794 795 796
    _dropdownRoute = null;
  }

  @override
797
  void didUpdateWidget(DropdownButton<T> oldWidget) {
798
    super.didUpdateWidget(oldWidget);
799
    _updateSelectedIndex();
800 801 802
  }

  void _updateSelectedIndex() {
803 804 805 806
    if (!_enabled) {
      return;
    }

807 808
    assert(widget.value == null ||
      widget.items.where((DropdownMenuItem<T> item) => item.value == widget.value).length == 1);
809
    _selectedIndex = null;
810 811
    for (int itemIndex = 0; itemIndex < widget.items.length; itemIndex++) {
      if (widget.items[itemIndex].value == widget.value) {
812 813 814 815 816 817
        _selectedIndex = itemIndex;
        return;
      }
    }
  }

818
  TextStyle get _textStyle => widget.style ?? Theme.of(context).textTheme.subhead;
819

820
  void _handleTap() {
821
    final RenderBox itemBox = context.findRenderObject();
822
    final Rect itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size;
823 824
    final TextDirection textDirection = Directionality.of(context);
    final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown
825
      ? _kAlignedMenuMargin
826
      : _kUnalignedMenuMargin;
827 828

    assert(_dropdownRoute == null);
829
    _dropdownRoute = _DropdownRoute<T>(
830
      items: widget.items,
831 832
      buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect),
      padding: _kMenuItemPadding.resolve(textDirection),
833
      selectedIndex: _selectedIndex ?? 0,
834
      elevation: widget.elevation,
835 836
      theme: Theme.of(context, shadowThemeOnly: true),
      style: _textStyle,
837
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
838 839
    );

840
    Navigator.push(context, _dropdownRoute).then<void>((_DropdownRouteResult<T> newValue) {
841
      _dropdownRoute = null;
842
      if (!mounted || newValue == null)
843
        return;
844 845
      if (widget.onChanged != null)
        widget.onChanged(newValue.result);
846 847 848
    });
  }

849 850 851 852 853
  // When isDense is true, reduce the height of this button from _kMenuItemHeight to
  // _kDenseButtonHeight, but don't make it smaller than the text that it contains.
  // Similarly, we don't reduce the height of the button so much that its icon
  // would be clipped.
  double get _denseButtonHeight {
854 855
    final double fontSize = _textStyle.fontSize ?? Theme.of(context).textTheme.subhead.fontSize;
    return math.max(fontSize, math.max(widget.iconSize, _kDenseButtonHeight));
856 857
  }

858
  Color get _iconColor {
859 860
    // These colors are not defined in the Material Design spec.
    if (_enabled) {
861
      if (widget.iconEnabledColor != null)
862 863
        return widget.iconEnabledColor;

864
      switch (Theme.of(context).brightness) {
865 866 867 868
        case Brightness.light:
          return Colors.grey.shade700;
        case Brightness.dark:
          return Colors.white70;
869 870
      }
    } else {
871
      if (widget.iconDisabledColor != null)
872 873
        return widget.iconDisabledColor;

874
      switch (Theme.of(context).brightness) {
875 876 877 878
        case Brightness.light:
          return Colors.grey.shade400;
        case Brightness.dark:
          return Colors.white10;
879 880
      }
    }
881 882 883

    assert(false);
    return null;
884 885 886 887
  }

  bool get _enabled => widget.items != null && widget.items.isNotEmpty && widget.onChanged != null;

888
  @override
889
  Widget build(BuildContext context) {
890
    assert(debugCheckHasMaterial(context));
891
    assert(debugCheckHasMaterialLocalizations(context));
892 893 894

    // The width of the button and the menu are defined by the widest
    // item and the width of the hint.
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
    List<Widget> items;
    if (_enabled) {
      items = widget.selectedItemBuilder == null
        ? List<Widget>.from(widget.items)
        : widget.selectedItemBuilder(context).map((Widget item) {
          return Container(
            height: _kMenuItemHeight,
            alignment: AlignmentDirectional.centerStart,
            child: item,
          );
        }).toList();
    } else {
      items = <Widget>[];
    }

910
    int hintIndex;
911
    if (widget.hint != null || (!_enabled && widget.disabledHint != null)) {
912 913 914
      final Widget emplacedHint = _enabled
        ? widget.hint
        : DropdownMenuItem<Widget>(child: widget.disabledHint ?? widget.hint);
915
      hintIndex = items.length;
916
      items.add(DefaultTextStyle(
917
        style: _textStyle.copyWith(color: Theme.of(context).hintColor),
918
        child: IgnorePointer(
919
          child: emplacedHint,
920
          ignoringSemantics: false,
921 922 923 924
        ),
      ));
    }

925 926 927 928
    final EdgeInsetsGeometry padding = ButtonTheme.of(context).alignedDropdown
      ? _kAlignedButtonPadding
      : _kUnalignedButtonPadding;

929 930
    // If value is null (then _selectedIndex is null) or if disabled then we
    // display the hint or nothing at all.
931 932 933 934 935 936 937 938 939 940 941
    final int index = _enabled ? (_selectedIndex ?? hintIndex) : hintIndex;
    Widget innerItemsWidget;
    if (items.isEmpty) {
      innerItemsWidget = Container();
    } else {
      innerItemsWidget = IndexedStack(
        index: index,
        alignment: AlignmentDirectional.centerStart,
        children: items,
      );
    }
942

943 944
    const Icon defaultIcon = Icon(Icons.arrow_drop_down);

945
    Widget result = DefaultTextStyle(
946
      style: _textStyle,
947
      child: Container(
948
        padding: padding.resolve(Directionality.of(context)),
949
        height: widget.isDense ? _denseButtonHeight : null,
950
        child: Row(
951 952 953
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
954 955 956
            widget.isExpanded
              ? Expanded(child: innerItemsWidget)
              : innerItemsWidget,
957 958 959 960 961 962
            IconTheme(
              data: IconThemeData(
                color: _iconColor,
                size: widget.iconSize,
              ),
              child: widget.icon ?? defaultIcon,
963 964 965 966
            ),
          ],
        ),
      ),
967
    );
968

969
    if (!DropdownButtonHideUnderline.at(context)) {
970
      final double bottom = widget.isDense ? 0.0 : 8.0;
971
      result = Stack(
972 973
        children: <Widget>[
          result,
974
          Positioned(
975 976
            left: 0.0,
            right: 0.0,
977
            bottom: bottom,
978
            child: widget.underline ?? Container(
979 980
              height: 1.0,
              decoration: const BoxDecoration(
981 982 983 984 985 986
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFBDBDBD),
                    width: 0.0,
                  ),
                ),
987 988 989 990
              ),
            ),
          ),
        ],
991 992
      );
    }
993

994
    return Semantics(
995
      button: true,
996
      child: GestureDetector(
997
        onTap: _enabled ? _handleTap : null,
998
        behavior: HitTestBehavior.opaque,
999
        child: result,
1000
      ),
1001 1002 1003
    );
  }
}
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

/// A convenience widget that wraps a [DropdownButton] in a [FormField].
class DropdownButtonFormField<T> extends FormField<T> {
  /// Creates a [DropdownButton] widget wrapped in an [InputDecorator] and
  /// [FormField].
  ///
  /// The [DropdownButton] [items] parameters must not be null.
  DropdownButtonFormField({
    Key key,
    T value,
    @required List<DropdownMenuItem<T>> items,
1015 1016 1017
    Widget hint,
    @required this.onChanged,
    this.decoration = const InputDecoration(),
1018 1019
    FormFieldSetter<T> onSaved,
    FormFieldValidator<T> validator,
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    bool autovalidate = false,
    Widget disabledHint,
    int elevation = 8,
    TextStyle style,
    Widget icon,
    Color iconDisabledColor,
    Color iconEnabledColor,
    double iconSize = 24.0,
    bool isDense = false,
    bool isExpanded = false,
  }) : assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1),
       assert(decoration != null),
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
1036 1037 1038 1039 1040
       super(
         key: key,
         onSaved: onSaved,
         initialValue: value,
         validator: validator,
1041
         autovalidate: autovalidate,
1042
         builder: (FormFieldState<T> field) {
1043 1044 1045
           final InputDecoration effectiveDecoration = decoration.applyDefaults(
             Theme.of(field.context).inputDecorationTheme,
           );
1046 1047 1048 1049 1050 1051 1052 1053
           return InputDecorator(
             decoration: effectiveDecoration.copyWith(errorText: field.errorText),
             isEmpty: value == null,
             child: DropdownButtonHideUnderline(
               child: DropdownButton<T>(
                 value: value,
                 items: items,
                 hint: hint,
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
                 onChanged: onChanged == null ? null : field.didChange,
                 disabledHint: disabledHint,
                 elevation: elevation,
                 style: style,
                 icon: icon,
                 iconDisabledColor: iconDisabledColor,
                 iconEnabledColor: iconEnabledColor,
                 iconSize: iconSize,
                 isDense: isDense,
                 isExpanded: isExpanded,
1064 1065 1066 1067 1068 1069
               ),
             ),
           );
         }
       );

1070
  /// {@macro flutter.material.dropdownButton.onChanged}
1071 1072
  final ValueChanged<T> onChanged;

1073 1074 1075 1076 1077 1078 1079 1080 1081
  /// The decoration to show around the dropdown button form field.
  ///
  /// By default, draws a horizontal line under the dropdown button field but can be
  /// configured to show an icon, label, hint text, and error text.
  ///
  /// Specify null to remove the decoration entirely (including the
  /// extra padding introduced by the decoration to save space for the labels).
  final InputDecoration decoration;

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
  @override
  FormFieldState<T> createState() => _DropdownButtonFormFieldState<T>();
}

class _DropdownButtonFormFieldState<T> extends FormFieldState<T> {
  @override
  DropdownButtonFormField<T> get widget => super.widget;

  @override
  void didChange(T value) {
    super.didChange(value);
1093 1094
    assert(widget.onChanged != null);
    widget.onChanged(value);
1095 1096
  }
}