dropdown.dart 53.8 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 'dart:math' as math;
6
import 'dart:ui' show window;
7

8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/services.dart';
11 12
import 'package:flutter/widgets.dart';

13
import 'button_theme.dart';
14
import 'colors.dart';
15
import 'constants.dart';
16
import 'debug.dart';
17
import 'icons.dart';
18
import 'ink_well.dart';
19
import 'input_decorator.dart';
20
import 'material.dart';
21
import 'material_localizations.dart';
22
import 'scrollbar.dart';
23 24 25
import 'shadows.dart';
import 'theme.dart';

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

35 36 37
/// A builder to customize dropdown buttons.
///
/// Used by [DropdownButton.selectedItemBuilder].
38 39
typedef DropdownButtonBuilder = List<Widget> Function(BuildContext context);

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

57 58 59
  final Color? color;
  final int? elevation;
  final int? selectedIndex;
60
  final Animation<double> resize;
61
  final ValueGetter<double> getSelectedItemOffset;
62
  final BoxPainter _painter;
63

64
  @override
65
  void paint(Canvas canvas, Size size) {
66
    final double selectedItemOffset = getSelectedItemOffset();
67
    final Tween<double> top = Tween<double>(
68
      begin: selectedItemOffset.clamp(0.0, size.height - _kMenuItemHeight),
69
      end: 0.0,
70 71
    );

72
    final Tween<double> bottom = Tween<double>(
73
      begin: (top.begin! + _kMenuItemHeight).clamp(_kMenuItemHeight, size.height),
74
      end: size.height,
75 76
    );

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

79
    _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
80 81
  }

82
  @override
83
  bool shouldRepaint(_DropdownMenuPainter oldPainter) {
84 85
    return oldPainter.color != color
        || oldPainter.elevation != elevation
86 87
        || oldPainter.selectedIndex != selectedIndex
        || oldPainter.resize != resize;
88 89 90
  }
}

91 92
// 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
93
class _DropdownScrollBehavior extends ScrollBehavior {
94
  const _DropdownScrollBehavior();
95 96

  @override
97
  TargetPlatform getPlatform(BuildContext context) => Theme.of(context).platform;
98 99

  @override
100
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) => child;
101 102

  @override
103
  ScrollPhysics getScrollPhysics(BuildContext context) => const ClampingScrollPhysics();
104 105
}

106 107 108
// The widget that is the button wrapping the menu items.
class _DropdownMenuItemButton<T> extends StatefulWidget {
  const _DropdownMenuItemButton({
109 110 111 112 113 114
    Key? key,
    this.padding,
    required this.route,
    required this.buttonRect,
    required this.constraints,
    required this.itemIndex,
115 116 117
  }) : super(key: key);

  final _DropdownRoute<T> route;
118 119 120
  final EdgeInsets? padding;
  final Rect? buttonRect;
  final BoxConstraints? constraints;
121 122 123 124 125 126 127 128
  final int itemIndex;

  @override
  _DropdownMenuItemButtonState<T> createState() => _DropdownMenuItemButtonState<T>();
}

class _DropdownMenuItemButtonState<T> extends State<_DropdownMenuItemButton<T>> {
  void _handleFocusChange(bool focused) {
129
    final bool inTraditionalMode;
130 131 132 133 134 135 136 137 138 139 140
    switch (FocusManager.instance.highlightMode) {
      case FocusHighlightMode.touch:
        inTraditionalMode = false;
        break;
      case FocusHighlightMode.traditional:
        inTraditionalMode = true;
        break;
    }

    if (focused && inTraditionalMode) {
      final _MenuLimits menuLimits = widget.route.getMenuLimits(
141 142
          widget.buttonRect!, widget.constraints!.maxHeight, widget.itemIndex);
      widget.route.scrollController!.animateTo(
143 144 145 146 147 148 149 150
        menuLimits.scrollOffset,
        curve: Curves.easeInOut,
        duration: const Duration(milliseconds: 100),
      );
    }
  }

  void _handleOnTap() {
151
    final DropdownMenuItem<T> dropdownMenuItem = widget.route.items[widget.itemIndex].item!;
152 153

    if (dropdownMenuItem.onTap != null) {
154
      dropdownMenuItem.onTap!();
155 156
    }

157 158
    Navigator.pop(
      context,
159
      _DropdownRouteResult<T>(dropdownMenuItem.value),
160 161 162 163
    );
  }

  static final Map<LogicalKeySet, Intent> _webShortcuts =<LogicalKeySet, Intent>{
164
    LogicalKeySet(LogicalKeyboardKey.enter): const ActivateIntent(),
165 166 167 168
  };

  @override
  Widget build(BuildContext context) {
169
    final CurvedAnimation opacity;
170 171
    final double unit = 0.5 / (widget.route.items.length + 1.5);
    if (widget.itemIndex == widget.route.selectedIndex) {
172
      opacity = CurvedAnimation(parent: widget.route.animation!, curve: const Threshold(0.0));
173
    } else {
174 175 176
      final double start = (0.5 + (widget.itemIndex + 1) * unit).clamp(0.0, 1.0);
      final double end = (start + 1.5 * unit).clamp(0.0, 1.0);
      opacity = CurvedAnimation(parent: widget.route.animation!, curve: Interval(start, end));
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    }
    Widget child = FadeTransition(
      opacity: opacity,
      child: InkWell(
        autofocus: widget.itemIndex == widget.route.selectedIndex,
        child: Container(
          padding: widget.padding,
          child: widget.route.items[widget.itemIndex],
        ),
        onTap: _handleOnTap,
        onFocusChange: _handleFocusChange,
      ),
    );
    if (kIsWeb) {
      // On the web, enter doesn't select things, *except* in a <select>
      // element, which is what a dropdown emulates.
      child = Shortcuts(
        shortcuts: _webShortcuts,
        child: child,
      );
    }
    return child;
  }
}

202
class _DropdownMenu<T> extends StatefulWidget {
203
  const _DropdownMenu({
204
    Key? key,
205
    this.padding,
206
    required this.route,
207 208
    this.buttonRect,
    this.constraints,
209
    this.dropdownColor,
210
  }) : super(key: key);
211

212
  final _DropdownRoute<T> route;
213 214 215 216
  final EdgeInsets? padding;
  final Rect? buttonRect;
  final BoxConstraints? constraints;
  final Color? dropdownColor;
217

218
  @override
219
  _DropdownMenuState<T> createState() => _DropdownMenuState<T>();
220 221
}

222
class _DropdownMenuState<T> extends State<_DropdownMenu<T>> {
223 224
  late CurvedAnimation _fadeOpacity;
  late CurvedAnimation _resize;
225 226 227 228 229 230 231 232

  @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.
233
    _fadeOpacity = CurvedAnimation(
234
      parent: widget.route.animation!,
235
      curve: const Interval(0.0, 0.25),
236
      reverseCurve: const Interval(0.75, 1.0),
237
    );
238
    _resize = CurvedAnimation(
239
      parent: widget.route.animation!,
240
      curve: const Interval(0.25, 0.5),
241
      reverseCurve: const Threshold(0.0),
242 243 244
    );
  }

245
  @override
246 247
  Widget build(BuildContext context) {
    // The menu is shown in three stages (unit timing in brackets):
Hixie's avatar
Hixie committed
248 249
    // [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
250
    //   until it's big enough for as many items as we're going to show.
Hixie's avatar
Hixie committed
251
    // [0.5s - 1.0s] Fade in the remaining visible items from top to bottom.
252 253
    //
    // When the menu is dismissed we just fade the entire thing out
Hixie's avatar
Hixie committed
254
    // in the first 0.25s.
255
    assert(debugCheckHasMaterialLocalizations(context));
256
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
257
    final _DropdownRoute<T> route = widget.route;
258 259 260 261 262 263 264 265
    final List<Widget> children = <Widget>[
      for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex)
        _DropdownMenuItemButton<T>(
          route: widget.route,
          padding: widget.padding,
          buttonRect: widget.buttonRect,
          constraints: widget.constraints,
          itemIndex: itemIndex,
266
        ),
267
      ];
268

269
    return FadeTransition(
270
      opacity: _fadeOpacity,
271 272
      child: CustomPaint(
        painter: _DropdownMenuPainter(
273
          color: widget.dropdownColor ?? Theme.of(context).canvasColor,
274 275
          elevation: route.elevation,
          selectedIndex: route.selectedIndex,
276
          resize: _resize,
277 278
          // This offset is passed as a callback, not a value, because it must
          // be retrieved at paint time (after layout), not at build time.
279
          getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex),
280
        ),
281
        child: Semantics(
282 283 284 285
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
286
          child: Material(
287 288 289 290 291 292 293 294 295 296
            type: MaterialType.transparency,
            textStyle: route.style,
            child: ScrollConfiguration(
              behavior: const _DropdownScrollBehavior(),
              child: Scrollbar(
                child: ListView(
                  controller: widget.route.scrollController,
                  padding: kMaterialListPadding,
                  shrinkWrap: true,
                  children: children,
297
                ),
298 299 300 301
              ),
            ),
          ),
        ),
302 303
      ),
    );
304 305 306
  }
}

307
class _DropdownMenuRouteLayout<T> extends SingleChildLayoutDelegate {
308
  _DropdownMenuRouteLayout({
309 310 311
    required this.buttonRect,
    required this.route,
    required this.textDirection,
312
  });
313

314
  final Rect buttonRect;
315
  final _DropdownRoute<T> route;
316
  final TextDirection? textDirection;
317 318 319

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
320 321 322
    // 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.
323
    //   -- https://material.io/design/components/menus.html#usage
324
    final double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight);
325 326
    // 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.
327
    final double width = math.min(constraints.maxWidth, buttonRect.width);
328
    return BoxConstraints(
329 330
      minWidth: width,
      maxWidth: width,
331
      minHeight: 0.0,
332
      maxHeight: maxHeight,
333 334 335 336 337
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
338
    final _MenuLimits menuLimits = route.getMenuLimits(buttonRect, size.height, route.selectedIndex);
339

340
    assert(() {
341
      final Rect container = Offset.zero & size;
342 343 344 345
      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.
346 347
        assert(menuLimits.top >= 0.0);
        assert(menuLimits.top + menuLimits.height <= size.height);
348 349
      }
      return true;
350
    }());
351
    assert(textDirection != null);
352
    final double left;
353
    switch (textDirection!) {
354
      case TextDirection.rtl:
355
        left = buttonRect.right.clamp(0.0, size.width) - childSize.width;
356 357
        break;
      case TextDirection.ltr:
358
        left = buttonRect.left.clamp(0.0, size.width - childSize.width);
359 360
        break;
    }
361 362

    return Offset(left, menuLimits.top);
363 364 365
  }

  @override
366
  bool shouldRelayout(_DropdownMenuRouteLayout<T> oldDelegate) {
367
    return buttonRect != oldDelegate.buttonRect || textDirection != oldDelegate.textDirection;
368
  }
369 370
}

371 372 373
// 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.
374
@immutable
375 376
class _DropdownRouteResult<T> {
  const _DropdownRouteResult(this.result);
377

378
  final T? result;
379 380

  @override
381
  bool operator ==(Object other) {
382 383
    return other is _DropdownRouteResult<T>
        && other.result == result;
384
  }
385 386

  @override
387 388 389
  int get hashCode => result.hashCode;
}

390 391 392 393 394 395 396 397
class _MenuLimits {
  const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset);
  final double top;
  final double bottom;
  final double height;
  final double scrollOffset;
}

398 399
class _DropdownRoute<T> extends PopupRoute<_DropdownRouteResult<T>> {
  _DropdownRoute({
400 401 402 403
    required this.items,
    required this.padding,
    required this.buttonRect,
    required this.selectedIndex,
404
    this.elevation = 8,
405
    required this.capturedThemes,
406
    required this.style,
407
    this.barrierLabel,
408
    this.itemHeight,
409
    this.dropdownColor,
410 411
  }) : assert(style != null),
       itemHeights = List<double>.filled(items.length, itemHeight ?? kMinInteractiveDimension);
412

413
  final List<_MenuItem<T>> items;
414
  final EdgeInsetsGeometry padding;
415
  final Rect buttonRect;
Hixie's avatar
Hixie committed
416
  final int selectedIndex;
Hans Muller's avatar
Hans Muller committed
417
  final int elevation;
418
  final CapturedThemes capturedThemes;
419
  final TextStyle style;
420 421
  final double? itemHeight;
  final Color? dropdownColor;
422

423
  final List<double> itemHeights;
424
  ScrollController? scrollController;
425

426
  @override
427
  Duration get transitionDuration => _kDropdownMenuDuration;
428 429

  @override
430
  bool get barrierDismissible => true;
431 432

  @override
433
  Color? get barrierColor => null;
434

435
  @override
436
  final String? barrierLabel;
437

438
  @override
439
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
440 441 442 443 444 445 446 447 448 449
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return _DropdownRoutePage<T>(
          route: this,
          constraints: constraints,
          items: items,
          padding: padding,
          buttonRect: buttonRect,
          selectedIndex: selectedIndex,
          elevation: elevation,
450
          capturedThemes: capturedThemes,
451
          style: style,
452
          dropdownColor: dropdownColor,
453 454 455 456 457 458
        );
      }
    );
  }

  void _dismiss() {
459 460 461
    if (isActive) {
      navigator?.removeRoute(this);
    }
462 463
  }

464
  double getItemOffset(int index) {
465
    double offset = kMaterialListPadding.top;
466
    if (items.isNotEmpty && index > 0) {
467
      assert(items.length == itemHeights.length);
468
      offset += itemHeights
469
        .sublist(0, index)
470 471 472 473
        .reduce((double total, double height) => total + height);
    }
    return offset;
  }
474

475 476 477 478
  // Returns the vertical extent of the menu and the initial scrollOffset
  // for the ListView that contains the menu items. The vertical center of the
  // selected item is aligned with the button's vertical center, as far as
  // that's possible given availableHeight.
479
  _MenuLimits getMenuLimits(Rect buttonRect, double availableHeight, int index) {
480
    final double maxMenuHeight = availableHeight - 2.0 * _kMenuItemHeight;
481
    final double buttonTop = buttonRect.top;
482
    final double buttonBottom = math.min(buttonRect.bottom, availableHeight);
483
    final double selectedItemOffset = getItemOffset(index);
484 485 486 487 488 489

    // 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);
490
    final double bottomLimit = math.max(availableHeight - _kMenuItemHeight, buttonBottom);
491

492 493 494 495
    double menuTop = (buttonTop - selectedItemOffset) - (itemHeights[selectedIndex] - buttonRect.height) / 2.0;
    double preferredMenuHeight = kMaterialListPadding.vertical;
    if (items.isNotEmpty)
      preferredMenuHeight += itemHeights.reduce((double total, double height) => total + height);
496 497 498 499 500 501 502 503 504 505 506 507 508

    // 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);
509

510 511 512
    if (menuBottom > bottomLimit) {
      menuBottom = math.max(buttonBottom, bottomLimit);
      menuTop = menuBottom - menuHeight;
513 514
    }

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    // If all of the menu items will not fit within availableHeight then
    // compute the scroll offset that will line the selected menu item up
    // with the select item. This is only done when the menu is first
    // shown - subsequently we leave the scroll offset where the user left
    // it. This scroll offset is only accurate for fixed height menu items
    // (the default).
    final double scrollOffset = preferredMenuHeight <= maxMenuHeight ? 0 :
      math.max(0.0, selectedItemOffset - (buttonTop - menuTop));

    return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset);
  }
}

class _DropdownRoutePage<T> extends StatelessWidget {
  const _DropdownRoutePage({
530 531 532
    Key? key,
    required this.route,
    required this.constraints,
533
    this.items,
534 535 536
    required this.padding,
    required this.buttonRect,
    required this.selectedIndex,
537
    this.elevation = 8,
538
    required this.capturedThemes,
539
    this.style,
540
    required this.dropdownColor,
541 542 543 544
  }) : super(key: key);

  final _DropdownRoute<T> route;
  final BoxConstraints constraints;
545
  final List<_MenuItem<T>>? items;
546 547 548 549
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final int selectedIndex;
  final int elevation;
550
  final CapturedThemes capturedThemes;
551 552
  final TextStyle? style;
  final Color? dropdownColor;
553 554 555 556 557 558 559 560 561 562 563

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasDirectionality(context));

    // Computing the initialScrollOffset now, before the items have been laid
    // out. This only works if the item heights are effectively fixed, i.e. either
    // DropdownButton.itemHeight is specified or DropdownButton.itemHeight is null
    // and all of the items' intrinsic heights are less than kMinInteractiveDimension.
    // Otherwise the initialScrollOffset is just a rough approximation based on
    // treating the items as if their heights were all equal to kMinInteractveDimension.
564
    if (route.scrollController == null) {
565
      final _MenuLimits menuLimits = route.getMenuLimits(buttonRect, constraints.maxHeight, selectedIndex);
566
      route.scrollController = ScrollController(initialScrollOffset: menuLimits.scrollOffset);
567 568
    }

569
    final TextDirection? textDirection = Directionality.maybeOf(context);
570
    final Widget menu = _DropdownMenu<T>(
571
      route: route,
572
      padding: padding.resolve(textDirection),
573 574
      buttonRect: buttonRect,
      constraints: constraints,
575
      dropdownColor: dropdownColor,
576 577
    );

578
    return MediaQuery.removePadding(
579 580 581 582 583
      context: context,
      removeTop: true,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
584
      child: Builder(
585
        builder: (BuildContext context) {
586 587
          return CustomSingleChildLayout(
            delegate: _DropdownMenuRouteLayout<T>(
588
              buttonRect: buttonRect,
589
              route: route,
590
              textDirection: textDirection,
591
            ),
592
            child: capturedThemes.wrap(menu),
593 594
          );
        },
595
      ),
596
    );
597
  }
598 599
}

600 601 602 603
// This widget enables _DropdownRoute to look up the sizes of
// each menu item. These sizes are used to compute the offset of the selected
// item so that _DropdownRoutePage can align the vertical center of the
// selected item lines up with the vertical center of the dropdown button,
604
// as closely as possible.
605 606
class _MenuItem<T> extends SingleChildRenderObjectWidget {
  const _MenuItem({
607 608 609
    Key? key,
    required this.onLayout,
    required this.item,
610 611 612
  }) : assert(onLayout != null), super(key: key, child: item);

  final ValueChanged<Size> onLayout;
613
  final DropdownMenuItem<T>? item;
614 615 616 617 618 619 620 621 622 623 624 625 626

  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderMenuItem(onLayout);
  }

  @override
  void updateRenderObject(BuildContext context, covariant _RenderMenuItem renderObject) {
    renderObject.onLayout = onLayout;
  }
}

class _RenderMenuItem extends RenderProxyBox {
627
  _RenderMenuItem(this.onLayout, [RenderBox? child]) : assert(onLayout != null), super(child);
628 629 630 631 632 633 634 635 636 637

  ValueChanged<Size> onLayout;

  @override
  void performLayout() {
    super.performLayout();
    onLayout(size);
  }
}

638 639 640 641
// The container widget for a menu item created by a [DropdownButton]. It
// provides the default configuration for [DropdownMenuItem]s, as well as a
// [DropdownButton]'s hint and disabledHint widgets.
class _DropdownMenuItemContainer extends StatelessWidget {
642
  /// Creates an item for a dropdown menu.
643 644
  ///
  /// The [child] argument is required.
645
  const _DropdownMenuItemContainer({
646 647
    Key? key,
    required this.child,
648 649
  }) : assert(child != null),
       super(key: key);
650

651
  /// The widget below this widget in the tree.
652 653
  ///
  /// Typically a [Text] widget.
654
  final Widget child;
655

656
  @override
657
  Widget build(BuildContext context) {
658
    return Container(
659
      constraints: const BoxConstraints(minHeight: _kMenuItemHeight),
660 661
      alignment: AlignmentDirectional.centerStart,
      child: child,
662 663 664 665
    );
  }
}

666 667 668 669 670 671 672 673 674
/// An item in a menu created by a [DropdownButton].
///
/// 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.
class DropdownMenuItem<T> extends _DropdownMenuItemContainer {
  /// Creates an item for a dropdown menu.
  ///
  /// The [child] argument is required.
  const DropdownMenuItem({
675
    Key? key,
676
    this.onTap,
677
    this.value,
678
    required Widget child,
679 680 681
  }) : assert(child != null),
       super(key: key, child: child);

682
  /// Called when the dropdown menu item is tapped.
683
  final VoidCallback? onTap;
684

685 686 687
  /// The value to return if the user selects this menu item.
  ///
  /// Eventually returned in a call to [DropdownButton.onChanged].
688
  final T? value;
689 690
}

691
/// An inherited widget that causes any descendant [DropdownButton]
692 693 694
/// widgets to not include their regular underline.
///
/// This is used by [DataTable] to remove the underline from any
695
/// [DropdownButton] widgets placed within material data tables, as
696
/// required by the material design specification.
697 698
class DropdownButtonHideUnderline extends InheritedWidget {
  /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must
699
  /// be given.
700
  const DropdownButtonHideUnderline({
701 702
    Key? key,
    required Widget child,
703 704
  }) : assert(child != null),
       super(key: key, child: child);
705

706
  /// Returns whether the underline of [DropdownButton] widgets should
707 708
  /// be hidden.
  static bool at(BuildContext context) {
709
    return context.dependOnInheritedWidgetOfExactType<DropdownButtonHideUnderline>() != null;
710 711 712
  }

  @override
713
  bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false;
714 715
}

716 717 718 719 720 721
/// 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.
///
722 723
/// 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.
724 725 726
/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be
/// specialized with that same type argument.
///
727 728 729 730
/// 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.
///
731
/// {@tool dartpad --template=stateful_widget_scaffold_center}
732
///
733 734 735
/// This sample shows a `DropdownButton` with a large arrow icon,
/// purple text style, and bold purple underline, whose value is one of "One",
/// "Two", "Free", or "Four".
736
///
737
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png)
738
///
739
/// ```dart
740 741
/// String dropdownValue = 'One';
///
742
/// @override
743
/// Widget build(BuildContext context) {
744 745 746 747 748 749 750
///   return DropdownButton<String>(
///     value: dropdownValue,
///     icon: Icon(Icons.arrow_downward),
///     iconSize: 24,
///     elevation: 16,
///     style: TextStyle(
///       color: Colors.deepPurple
751
///     ),
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
///     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(),
769 770 771 772 773 774 775 776
///   );
/// }
/// ```
/// {@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
777 778 779
/// will display the [disabledHint] widget if it is non-null. However, if
/// [disabledHint] is null and [hint] is non-null, the [hint] widget will
/// instead be displayed.
780
///
781 782 783
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
784
///
785
///  * [DropdownMenuItem], the class used to represent the [items].
786
///  * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons
787
///    from displaying their underlines.
788
///  * [ElevatedButton], [TextButton], ordinary buttons that trigger a single action.
789
///  * <https://material.io/design/components/menus.html#dropdown-menu>
790
class DropdownButton<T> extends StatefulWidget {
791
  /// Creates a dropdown button.
792
  ///
793
  /// The [items] must have distinct values. If [value] isn't null then it
794
  /// must be equal to one of the [DropdownMenuItem] values. If [items] or
795 796
  /// [onChanged] is null, the button will be disabled, the down arrow
  /// will be greyed out, and the [disabledHint] will be shown (if provided).
797 798
  /// If [disabledHint] is null and [hint] is non-null, [hint] will instead be
  /// shown.
799 800
  ///
  /// The [elevation] and [iconSize] arguments must not be null (they both have
801 802
  /// defaults, so do not need to be specified). The boolean [isDense] and
  /// [isExpanded] arguments must not be null.
803
  ///
804 805
  /// The [autofocus] argument must not be null.
  ///
806 807 808
  /// The [dropdownColor] argument specifies the background color of the
  /// dropdown when it is open. If it is null, the current theme's
  /// [ThemeData.canvasColor] will be used instead.
809
  DropdownButton({
810 811
    Key? key,
    required this.items,
812
    this.selectedItemBuilder,
813
    this.value,
814
    this.hint,
815
    this.disabledHint,
816
    required this.onChanged,
817
    this.onTap,
818
    this.elevation = 8,
819
    this.style,
820
    this.underline,
821 822 823
    this.icon,
    this.iconDisabledColor,
    this.iconEnabledColor,
824 825
    this.iconSize = 24.0,
    this.isDense = false,
826
    this.isExpanded = false,
827
    this.itemHeight = kMinInteractiveDimension,
828 829 830
    this.focusColor,
    this.focusNode,
    this.autofocus = false,
831
    this.dropdownColor,
832 833
    // When adding new arguments, consider adding similar arguments to
    // DropdownButtonFormField.
834 835 836 837
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
838
                "There should be exactly one item with [DropdownButton]'s value: "
839 840 841 842
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
843 844 845 846
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
847
       assert(autofocus != null),
848
       assert(itemHeight == null || itemHeight >=  kMinInteractiveDimension),
849
       super(key: key);
850

851 852 853 854 855
  /// 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
856 857 858
  /// will display the [disabledHint] widget if it is non-null. If
  /// [disabledHint] is also null but [hint] is non-null, [hint] will instead
  /// be displayed.
859
  final List<DropdownMenuItem<T>>? items;
860

861 862 863 864
  /// The value of the currently selected [DropdownMenuItem].
  ///
  /// If [value] is null and [hint] is non-null, the [hint] widget is
  /// displayed as a placeholder for the dropdown button's value.
865
  final T? value;
866

867 868 869 870 871
  /// A placeholder widget that is displayed by the dropdown button.
  ///
  /// If [value] is null, this widget is displayed as a placeholder for
  /// the dropdown button's value. This widget is also displayed if the button
  /// is disabled ([items] or [onChanged] is null) and [disabledHint] is null.
872
  final Widget? hint;
873

874 875
  /// A message to show when the dropdown is disabled.
  ///
876 877
  /// Displayed if [items] or [onChanged] is null. If [hint] is non-null and
  /// [disabledHint] is null, the [hint] widget will be displayed instead.
878
  final Widget? disabledHint;
879

880
  /// {@template flutter.material.dropdownButton.onChanged}
881
  /// Called when the user selects an item.
882
  ///
883 884
  /// If the [onChanged] callback is null or the list of [DropdownButton.items]
  /// is null then the dropdown button will be disabled, i.e. its arrow will be
885
  /// displayed in grey and it will not respond to input. A disabled button
886 887 888
  /// will display the [DropdownButton.disabledHint] widget if it is non-null.
  /// If [DropdownButton.disabledHint] is also null but [DropdownButton.hint] is
  /// non-null, [DropdownButton.hint] will instead be displayed.
889
  /// {@endtemplate}
890
  final ValueChanged<T?>? onChanged;
891

892 893 894 895 896 897
  /// Called when the dropdown button is tapped.
  ///
  /// This is distinct from [onChanged], which is called when the user
  /// selects an item from the dropdown.
  ///
  /// The callback will not be invoked if the dropdown button is disabled.
898
  final VoidCallback? onTap;
899

900 901 902 903 904 905 906
  /// 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].
  ///
907
  /// {@tool dartpad --template=stateful_widget_scaffold}
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  ///
  /// 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) {
924
  ///         return items.map<Widget>((String item) {
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
  ///           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.
942
  final DropdownButtonBuilder? selectedItemBuilder;
943

944
  /// The z-coordinate at which to place the menu when open.
945
  ///
946 947
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12,
  /// 16, and 24. See [kElevationToShadow].
948 949
  ///
  /// Defaults to 8, the appropriate elevation for dropdown buttons.
Hans Muller's avatar
Hans Muller committed
950
  final int elevation;
951

952
  /// The text style to use for text in the dropdown button and the dropdown
953 954
  /// menu that appears when you tap the button.
  ///
955
  /// To use a separate text style for selected item when it's displayed within
956
  /// the dropdown button, consider using [selectedItemBuilder].
957
  ///
958
  /// {@tool dartpad --template=stateful_widget_scaffold}
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
  ///
  /// This sample shows a `DropdownButton` with a dropdown button text style
  /// that is different than its menu items.
  ///
  /// ```dart
  /// List<String> options = <String>['One', 'Two', 'Free', 'Four'];
  /// String dropdownValue = 'One';
  ///
  /// @override
  /// Widget build(BuildContext context) {
  ///   return Container(
  ///     alignment: Alignment.center,
  ///     color: Colors.blue,
  ///     child: DropdownButton<String>(
  ///       value: dropdownValue,
  ///       onChanged: (String newValue) {
  ///         setState(() {
  ///           dropdownValue = newValue;
  ///         });
  ///       },
  ///       style: TextStyle(color: Colors.blue),
  ///       selectedItemBuilder: (BuildContext context) {
  ///         return options.map((String value) {
  ///           return Text(
  ///             dropdownValue,
  ///             style: TextStyle(color: Colors.white),
  ///           );
  ///         }).toList();
  ///       },
  ///       items: options.map<DropdownMenuItem<String>>((String value) {
  ///         return DropdownMenuItem<String>(
  ///           value: value,
  ///           child: Text(value),
  ///         );
  ///       }).toList(),
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
1000
  /// Defaults to the [TextTheme.subtitle1] value of the current
1001
  /// [ThemeData.textTheme] of the current [Theme].
1002
  final TextStyle? style;
1003

1004 1005 1006
  /// The widget to use for drawing the drop-down button's underline.
  ///
  /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD.
1007
  final Widget? underline;
1008

1009 1010 1011
  /// The widget to use for the drop-down button's icon.
  ///
  /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph.
1012
  final Widget? icon;
1013 1014 1015 1016

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

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

1030 1031
  /// The size to use for the drop-down button's down arrow icon button.
  ///
1032
  /// Defaults to 24.0.
1033 1034
  final double iconSize;

1035 1036 1037 1038 1039
  /// 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
1040
  /// its own decorations, like [InputDecorator].
1041 1042
  final bool isDense;

1043 1044 1045 1046 1047 1048 1049
  /// 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;

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  /// If null, then the menu item heights will vary according to each menu item's
  /// intrinsic height.
  ///
  /// The default value is [kMinInteractiveDimension], which is also the minimum
  /// height for menu items.
  ///
  /// If this value is null and there isn't enough vertical room for the menu,
  /// then the menu's initial scroll offset may not align the selected item with
  /// the dropdown button. That's because, in this case, the initial scroll
  /// offset is computed as if all of the menu item heights were
  /// [kMinInteractiveDimension].
1061
  final double? itemHeight;
1062

1063
  /// The color for the button's [Material] when it has the input focus.
1064
  final Color? focusColor;
1065 1066

  /// {@macro flutter.widgets.Focus.focusNode}
1067
  final FocusNode? focusNode;
1068 1069 1070 1071

  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

1072 1073 1074 1075
  /// The background color of the dropdown.
  ///
  /// If it is not provided, the theme's [ThemeData.canvasColor] will be used
  /// instead.
1076
  final Color? dropdownColor;
1077

1078
  @override
1079
  _DropdownButtonState<T> createState() => _DropdownButtonState<T>();
1080 1081
}

1082
class _DropdownButtonState<T> extends State<DropdownButton<T>> with WidgetsBindingObserver {
1083 1084 1085 1086 1087
  int? _selectedIndex;
  _DropdownRoute<T>? _dropdownRoute;
  Orientation? _lastOrientation;
  FocusNode? _internalNode;
  FocusNode? get focusNode => widget.focusNode ?? _internalNode;
1088
  bool _hasPrimaryFocus = false;
1089 1090
  late Map<Type, Action<Intent>> _actionMap;
  late FocusHighlightMode _focusHighlightMode;
1091 1092 1093 1094 1095

  // Only used if needed to create _internalNode.
  FocusNode _createFocusNode() {
    return FocusNode(debugLabel: '${widget.runtimeType}');
  }
1096

1097
  @override
1098 1099 1100
  void initState() {
    super.initState();
    _updateSelectedIndex();
1101 1102 1103
    if (widget.focusNode == null) {
      _internalNode ??= _createFocusNode();
    }
1104 1105 1106 1107
    _actionMap = <Type, Action<Intent>>{
      ActivateIntent: CallbackAction<ActivateIntent>(
        onInvoke: (ActivateIntent intent) => _handleTap(),
      ),
1108
    };
1109 1110
    focusNode!.addListener(_handleFocusChanged);
    final FocusManager focusManager = WidgetsBinding.instance!.focusManager;
1111 1112
    _focusHighlightMode = focusManager.highlightMode;
    focusManager.addHighlightModeListener(_handleFocusHighlightModeChange);
1113 1114
  }

1115 1116
  @override
  void dispose() {
1117
    WidgetsBinding.instance!.removeObserver(this);
1118
    _removeDropdownRoute();
1119 1120
    WidgetsBinding.instance!.focusManager.removeHighlightModeListener(_handleFocusHighlightModeChange);
    focusNode!.removeListener(_handleFocusChanged);
1121
    _internalNode?.dispose();
1122 1123 1124
    super.dispose();
  }

1125 1126
  void _removeDropdownRoute() {
    _dropdownRoute?._dismiss();
1127
    _dropdownRoute = null;
1128
    _lastOrientation = null;
1129 1130
  }

1131
  void _handleFocusChanged() {
1132
    if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) {
1133
      setState(() {
1134
        _hasPrimaryFocus = focusNode!.hasPrimaryFocus;
1135 1136 1137 1138
      });
    }
  }

1139 1140 1141 1142 1143 1144 1145 1146 1147
  void _handleFocusHighlightModeChange(FocusHighlightMode mode) {
    if (!mounted) {
      return;
    }
    setState(() {
      _focusHighlightMode = mode;
    });
  }

1148
  @override
1149
  void didUpdateWidget(DropdownButton<T> oldWidget) {
1150
    super.didUpdateWidget(oldWidget);
1151 1152 1153 1154 1155
    if (widget.focusNode != oldWidget.focusNode) {
      oldWidget.focusNode?.removeListener(_handleFocusChanged);
      if (widget.focusNode == null) {
        _internalNode ??= _createFocusNode();
      }
1156 1157
      _hasPrimaryFocus = focusNode!.hasPrimaryFocus;
      focusNode!.addListener(_handleFocusChanged);
1158
    }
1159
    _updateSelectedIndex();
1160 1161 1162
  }

  void _updateSelectedIndex() {
1163 1164 1165 1166
    if (!_enabled) {
      return;
    }

1167
    assert(widget.value == null ||
1168
      widget.items!.where((DropdownMenuItem<T> item) => item.value == widget.value).length == 1);
1169
    _selectedIndex = null;
1170 1171
    for (int itemIndex = 0; itemIndex < widget.items!.length; itemIndex++) {
      if (widget.items![itemIndex].value == widget.value) {
1172 1173 1174 1175 1176 1177
        _selectedIndex = itemIndex;
        return;
      }
    }
  }

1178
  TextStyle? get _textStyle => widget.style ?? Theme.of(context).textTheme.subtitle1;
1179

1180
  void _handleTap() {
1181
    final RenderBox itemBox = context.findRenderObject()! as RenderBox;
1182
    final Rect itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size;
1183
    final TextDirection? textDirection = Directionality.maybeOf(context);
1184
    final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown
1185
      ? _kAlignedMenuMargin
1186
      : _kUnalignedMenuMargin;
1187

1188 1189 1190 1191
    final List<_MenuItem<T>> menuItems = <_MenuItem<T>>[
    for (int index = 0; index < widget.items!.length; index += 1)
      _MenuItem<T>(
        item: widget.items![index],
1192
        onLayout: (Size size) {
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
          // If [_dropdownRoute] is null and onLayout is called, this means
          // that performLayout was called on a _DropdownRoute that has not
          // left the widget tree but is already on its way out.
          //
          // Since onLayout is used primarily to collect the desired heights
          // of each menu item before laying them out, not having the _DropdownRoute
          // collect each item's height to lay out is fine since the route is
          // already on its way out.
          if (_dropdownRoute == null)
            return;

1204
          _dropdownRoute!.itemHeights[index] = size.height;
1205
        },
1206 1207
      )
    ];
1208

1209
    final NavigatorState navigator = Navigator.of(context)!;
1210
    assert(_dropdownRoute == null);
1211
    _dropdownRoute = _DropdownRoute<T>(
1212
      items: menuItems,
1213 1214
      buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect),
      padding: _kMenuItemPadding.resolve(textDirection),
1215
      selectedIndex: _selectedIndex ?? 0,
1216
      elevation: widget.elevation,
1217
      capturedThemes: InheritedTheme.capture(from: context, to: navigator.context),
1218
      style: _textStyle!,
1219
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
1220
      itemHeight: widget.itemHeight,
1221
      dropdownColor: widget.dropdownColor,
1222 1223
    );

1224
    navigator.push(_dropdownRoute!).then<void>((_DropdownRouteResult<T>? newValue) {
1225
      _removeDropdownRoute();
1226
      if (!mounted || newValue == null)
1227
        return;
1228
      if (widget.onChanged != null)
1229
        widget.onChanged!(newValue.result);
1230
    });
1231 1232

    if (widget.onTap != null) {
1233
      widget.onTap!();
1234
    }
1235 1236
  }

1237 1238 1239 1240 1241
  // 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 {
1242
    final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.subtitle1!.fontSize!;
1243
    return math.max(fontSize, math.max(widget.iconSize, _kDenseButtonHeight));
1244 1245
  }

1246
  Color get _iconColor {
1247 1248
    // These colors are not defined in the Material Design spec.
    if (_enabled) {
1249
      if (widget.iconEnabledColor != null)
1250
        return widget.iconEnabledColor!;
1251

1252
      switch (Theme.of(context).brightness) {
1253 1254 1255 1256
        case Brightness.light:
          return Colors.grey.shade700;
        case Brightness.dark:
          return Colors.white70;
1257 1258
      }
    } else {
1259
      if (widget.iconDisabledColor != null)
1260
        return widget.iconDisabledColor!;
1261

1262
      switch (Theme.of(context).brightness) {
1263 1264 1265 1266
        case Brightness.light:
          return Colors.grey.shade400;
        case Brightness.dark:
          return Colors.white10;
1267 1268 1269 1270
      }
    }
  }

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

1273
  Orientation _getOrientation(BuildContext context) {
1274
    Orientation? result = MediaQuery.maybeOf(context)?.orientation;
1275 1276 1277 1278 1279 1280 1281 1282 1283
    if (result == null) {
      // If there's no MediaQuery, then use the window aspect to determine
      // orientation.
      final Size size = window.physicalSize;
      result = size.width > size.height ? Orientation.landscape : Orientation.portrait;
    }
    return result;
  }

1284 1285 1286 1287 1288 1289 1290 1291 1292
  bool get _showHighlight {
    switch (_focusHighlightMode) {
      case FocusHighlightMode.touch:
        return false;
      case FocusHighlightMode.traditional:
        return _hasPrimaryFocus;
    }
  }

1293
  @override
1294
  Widget build(BuildContext context) {
1295
    assert(debugCheckHasMaterial(context));
1296
    assert(debugCheckHasMaterialLocalizations(context));
1297 1298 1299 1300 1301 1302
    final Orientation newOrientation = _getOrientation(context);
    _lastOrientation ??= newOrientation;
    if (newOrientation != _lastOrientation) {
      _removeDropdownRoute();
      _lastOrientation = newOrientation;
    }
1303 1304 1305

    // The width of the button and the menu are defined by the widest
    // item and the width of the hint.
1306 1307 1308 1309 1310 1311
    // We should explicitly type the items list to be a list of <Widget>,
    // otherwise, no explicit type adding items maybe trigger a crash/failure
    // when hint and selectedItemBuilder are provided.
    final List<Widget> items = widget.selectedItemBuilder == null
      ? (_enabled ? List<Widget>.from(widget.items!) : <Widget>[])
      : List<Widget>.from(widget.selectedItemBuilder!(context));
1312

1313
    int? hintIndex;
1314
    if (widget.hint != null || (!_enabled && widget.disabledHint != null)) {
1315
      Widget displayedHint = _enabled ? widget.hint! : widget.disabledHint ?? widget.hint!;
1316 1317 1318
      if (widget.selectedItemBuilder == null)
        displayedHint = _DropdownMenuItemContainer(child: displayedHint);

1319
      hintIndex = items.length;
1320
      items.add(DefaultTextStyle(
1321
        style: _textStyle!.copyWith(color: Theme.of(context).hintColor),
1322
        child: IgnorePointer(
1323
          ignoringSemantics: false,
1324
          child: displayedHint,
1325 1326 1327 1328
        ),
      ));
    }

1329 1330 1331 1332
    final EdgeInsetsGeometry padding = ButtonTheme.of(context).alignedDropdown
      ? _kAlignedButtonPadding
      : _kUnalignedButtonPadding;

1333 1334
    // If value is null (then _selectedIndex is null) or if disabled then we
    // display the hint or nothing at all.
1335
    final int? index = _enabled ? (_selectedIndex ?? hintIndex) : hintIndex;
1336
    final Widget innerItemsWidget;
1337 1338 1339 1340 1341 1342
    if (items.isEmpty) {
      innerItemsWidget = Container();
    } else {
      innerItemsWidget = IndexedStack(
        index: index,
        alignment: AlignmentDirectional.centerStart,
1343 1344 1345 1346 1347
        children: widget.isDense ? items : items.map((Widget item) {
          return widget.itemHeight != null
            ? SizedBox(height: widget.itemHeight, child: item)
            : Column(mainAxisSize: MainAxisSize.min, children: <Widget>[item]);
        }).toList(),
1348 1349
      );
    }
1350

1351 1352
    const Icon defaultIcon = Icon(Icons.arrow_drop_down);

1353
    Widget result = DefaultTextStyle(
1354
      style: _textStyle!,
1355
      child: Container(
1356 1357
        decoration: _showHighlight
            ? BoxDecoration(
1358
                color: widget.focusColor ?? Theme.of(context).focusColor,
1359 1360 1361
                borderRadius: const BorderRadius.all(Radius.circular(4.0)),
              )
            : null,
1362
        padding: padding.resolve(Directionality.of(context)),
1363
        height: widget.isDense ? _denseButtonHeight : null,
1364
        child: Row(
1365 1366 1367
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
1368 1369 1370 1371
            if (widget.isExpanded)
              Expanded(child: innerItemsWidget)
            else
              innerItemsWidget,
1372 1373 1374 1375 1376 1377
            IconTheme(
              data: IconThemeData(
                color: _iconColor,
                size: widget.iconSize,
              ),
              child: widget.icon ?? defaultIcon,
1378 1379 1380 1381
            ),
          ],
        ),
      ),
1382
    );
1383

1384
    if (!DropdownButtonHideUnderline.at(context)) {
1385
      final double bottom = (widget.isDense || widget.itemHeight == null) ? 0.0 : 8.0;
1386
      result = Stack(
1387 1388
        children: <Widget>[
          result,
1389
          Positioned(
1390 1391
            left: 0.0,
            right: 0.0,
1392
            bottom: bottom,
1393
            child: widget.underline ?? Container(
1394 1395
              height: 1.0,
              decoration: const BoxDecoration(
1396 1397 1398 1399 1400 1401
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFBDBDBD),
                    width: 0.0,
                  ),
                ),
1402 1403 1404 1405
              ),
            ),
          ),
        ],
1406 1407
      );
    }
1408

1409
    return Semantics(
1410
      button: true,
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
      child: Actions(
        actions: _actionMap,
        child: Focus(
          canRequestFocus: _enabled,
          focusNode: focusNode,
          autofocus: widget.autofocus,
          child: GestureDetector(
            onTap: _enabled ? _handleTap : null,
            behavior: HitTestBehavior.opaque,
            child: result,
          ),
        ),
1423
      ),
1424 1425 1426
    );
  }
}
1427

1428
/// A convenience widget that makes a [DropdownButton] into a [FormField].
1429
class DropdownButtonFormField<T> extends FormField<T> {
1430 1431 1432
  /// Creates a [DropdownButton] widget that is a [FormField], wrapped in an
  /// [InputDecorator].
  ///
1433
  /// For a description of the `onSaved`, `validator`, or `autovalidateMode`
1434 1435
  /// parameters, see [FormField]. For the rest (other than [decoration]), see
  /// [DropdownButton].
1436
  ///
1437 1438
  /// The `items`, `elevation`, `iconSize`, `isDense`, `isExpanded`,
  /// `autofocus`, and `decoration`  parameters must not be null.
1439
  DropdownButtonFormField({
1440 1441 1442 1443 1444 1445 1446 1447
    Key? key,
    required List<DropdownMenuItem<T>>? items,
    DropdownButtonBuilder? selectedItemBuilder,
    T? value,
    Widget? hint,
    Widget? disabledHint,
    required this.onChanged,
    VoidCallback? onTap,
1448
    int elevation = 8,
1449 1450 1451 1452
    TextStyle? style,
    Widget? icon,
    Color? iconDisabledColor,
    Color? iconEnabledColor,
1453
    double iconSize = 24.0,
1454
    bool isDense = true,
1455
    bool isExpanded = false,
1456 1457 1458
    double? itemHeight,
    Color? focusColor,
    FocusNode? focusNode,
1459
    bool autofocus = false,
1460 1461 1462 1463
    Color? dropdownColor,
    InputDecoration? decoration,
    FormFieldSetter<T>? onSaved,
    FormFieldValidator<T>? validator,
1464 1465 1466 1467 1468
    @Deprecated(
      'Use autoValidateMode parameter which provide more specific '
      'behaviour related to auto validation. '
      'This feature was deprecated after v1.19.0.'
    )
1469
    bool autovalidate = false,
1470
    AutovalidateMode? autovalidateMode,
1471 1472 1473 1474
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
1475
                "There should be exactly one item with [DropdownButton]'s value: "
1476 1477 1478 1479
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
1480 1481 1482 1483
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
1484 1485
       assert(itemHeight == null || itemHeight >= kMinInteractiveDimension),
       assert(autofocus != null),
1486 1487 1488 1489 1490 1491
       assert(autovalidate != null),
       assert(
         autovalidate == false ||
         autovalidate == true && autovalidateMode == null,
         'autovalidate and autovalidateMode should not be used together.'
       ),
1492
       decoration = decoration ?? InputDecoration(focusColor: focusColor),
1493 1494 1495 1496 1497
       super(
         key: key,
         onSaved: onSaved,
         initialValue: value,
         validator: validator,
1498 1499 1500
         autovalidateMode: autovalidate
             ? AutovalidateMode.always
             : (autovalidateMode ?? AutovalidateMode.disabled),
1501
         builder: (FormFieldState<T> field) {
1502
           final _DropdownButtonFormFieldState<T> state = field as _DropdownButtonFormFieldState<T>;
1503 1504
           final InputDecoration decorationArg =  decoration ?? InputDecoration(focusColor: focusColor);
           final InputDecoration effectiveDecoration = decorationArg.applyDefaults(
1505
             Theme.of(field.context).inputDecorationTheme,
1506
           );
1507 1508 1509 1510 1511 1512 1513 1514 1515
           // An unfocusable Focus widget so that this widget can detect if its
           // descendants have focus or not.
           return Focus(
             canRequestFocus: false,
             skipTraversal: true,
             child: Builder(builder: (BuildContext context) {
               return InputDecorator(
                 decoration: effectiveDecoration.copyWith(errorText: field.errorText),
                 isEmpty: state.value == null,
1516
                 isFocused: Focus.of(context).hasFocus,
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
                 child: DropdownButtonHideUnderline(
                   child: DropdownButton<T>(
                     items: items,
                     selectedItemBuilder: selectedItemBuilder,
                     value: state.value,
                     hint: hint,
                     disabledHint: disabledHint,
                     onChanged: onChanged == null ? null : state.didChange,
                     onTap: onTap,
                     elevation: elevation,
                     style: style,
                     icon: icon,
                     iconDisabledColor: iconDisabledColor,
                     iconEnabledColor: iconEnabledColor,
                     iconSize: iconSize,
                     isDense: isDense,
                     isExpanded: isExpanded,
                     itemHeight: itemHeight,
                     focusColor: focusColor,
                     focusNode: focusNode,
                     autofocus: autofocus,
                     dropdownColor: dropdownColor,
                   ),
                 ),
               );
             }),
1543
           );
1544
         },
1545 1546
       );

1547
  /// {@macro flutter.material.dropdownButton.onChanged}
1548
  final ValueChanged<T?>? onChanged;
1549

1550 1551
  /// The decoration to show around the dropdown button form field.
  ///
1552 1553
  /// 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.
1554
  ///
1555 1556
  /// If not specified, an [InputDecorator] with the `focusColor` set to the
  /// supplied `focusColor` (if any) will be used.
1557 1558
  final InputDecoration decoration;

1559 1560 1561 1562 1563 1564
  @override
  FormFieldState<T> createState() => _DropdownButtonFormFieldState<T>();
}

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

  @override
1568
  void didChange(T? value) {
1569
    super.didChange(value);
1570
    assert(widget.onChanged != null);
1571
    widget.onChanged!(value);
1572
  }
1573 1574 1575 1576 1577 1578 1579 1580

  @override
  void didUpdateWidget(DropdownButtonFormField<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.initialValue != widget.initialValue) {
      setValue(widget.initialValue);
    }
  }
1581
}