dropdown.dart 58.9 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

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

12
import 'button_theme.dart';
13
import 'colors.dart';
14
import 'constants.dart';
15
import 'debug.dart';
16
import 'icons.dart';
17
import 'ink_well.dart';
18
import 'input_decorator.dart';
19
import 'material.dart';
20
import 'material_localizations.dart';
21
import 'material_state.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
    this.borderRadius,
46 47
    required this.resize,
    required this.getSelectedItemOffset,
48
  }) : _painter = BoxDecoration(
49
         // If you add an image here, you must provide a real
50 51
         // configuration in the paint() function and you must provide some sort
         // of onChanged callback here.
52
         color: color,
53
         borderRadius: borderRadius ?? const BorderRadius.all(Radius.circular(2.0)),
54
         boxShadow: kElevationToShadow[elevation],
55 56
       ).createBoxPainter(),
       super(repaint: resize);
57

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

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

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

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

81
    _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
82 83
  }

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

94 95 96
// The widget that is the button wrapping the menu items.
class _DropdownMenuItemButton<T> extends StatefulWidget {
  const _DropdownMenuItemButton({
97 98 99 100 101 102
    Key? key,
    this.padding,
    required this.route,
    required this.buttonRect,
    required this.constraints,
    required this.itemIndex,
103
    required this.enableFeedback,
104 105 106
  }) : super(key: key);

  final _DropdownRoute<T> route;
107
  final EdgeInsets? padding;
108 109
  final Rect buttonRect;
  final BoxConstraints constraints;
110
  final int itemIndex;
111
  final bool enableFeedback;
112 113 114 115 116 117 118

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

class _DropdownMenuItemButtonState<T> extends State<_DropdownMenuItemButton<T>> {
  void _handleFocusChange(bool focused) {
119
    final bool inTraditionalMode;
120 121 122 123 124 125 126 127 128 129 130
    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(
131 132 133 134
        widget.buttonRect,
        widget.constraints.maxHeight,
        widget.itemIndex,
      );
135
      widget.route.scrollController!.animateTo(
136 137 138 139 140 141 142 143
        menuLimits.scrollOffset,
        curve: Curves.easeInOut,
        duration: const Duration(milliseconds: 100),
      );
    }
  }

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

146
    dropdownMenuItem.onTap?.call();
147

148 149
    Navigator.pop(
      context,
150
      _DropdownRouteResult<T>(dropdownMenuItem.value),
151 152 153
    );
  }

154
  static const Map<ShortcutActivator, Intent> _webShortcuts = <ShortcutActivator, Intent>{
155 156
    // On the web, up/down don't change focus, *except* in a <select>
    // element, which is what a dropdown emulates.
157 158
    SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
    SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
159 160 161 162
  };

  @override
  Widget build(BuildContext context) {
163
    final DropdownMenuItem<T> dropdownMenuItem = widget.route.items[widget.itemIndex].item!;
164
    final CurvedAnimation opacity;
165 166
    final double unit = 0.5 / (widget.route.items.length + 1.5);
    if (widget.itemIndex == widget.route.selectedIndex) {
167
      opacity = CurvedAnimation(parent: widget.route.animation!, curve: const Threshold(0.0));
168
    } else {
169 170 171
      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));
172
    }
173 174
    Widget child = Container(
      padding: widget.padding,
175
      height: widget.route.itemHeight,
176 177 178 179 180
      child: widget.route.items[widget.itemIndex],
    );
    // An [InkWell] is added to the item only if it is enabled
    if (dropdownMenuItem.enabled) {
      child = InkWell(
181
        autofocus: widget.itemIndex == widget.route.selectedIndex,
182
        enableFeedback: widget.enableFeedback,
183 184
        onTap: _handleOnTap,
        onFocusChange: _handleFocusChange,
185
        child: child,
186 187 188 189
      );
    }
    child = FadeTransition(opacity: opacity, child: child);
    if (kIsWeb && dropdownMenuItem.enabled) {
190 191 192 193 194 195 196 197 198
      child = Shortcuts(
        shortcuts: _webShortcuts,
        child: child,
      );
    }
    return child;
  }
}

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

211
  final _DropdownRoute<T> route;
212
  final EdgeInsets? padding;
213 214
  final Rect buttonRect;
  final BoxConstraints constraints;
215
  final Color? dropdownColor;
216
  final bool enableFeedback;
217
  final BorderRadius? borderRadius;
218

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

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

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

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

271
    return FadeTransition(
272
      opacity: _fadeOpacity,
273 274
      child: CustomPaint(
        painter: _DropdownMenuPainter(
275
          color: widget.dropdownColor ?? Theme.of(context).canvasColor,
276 277
          elevation: route.elevation,
          selectedIndex: route.selectedIndex,
278
          resize: _resize,
279
          borderRadius: widget.borderRadius,
280 281
          // This offset is passed as a callback, not a value, because it must
          // be retrieved at paint time (after layout), not at build time.
282
          getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex),
283
        ),
284
        child: Semantics(
285 286 287 288
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
289
          child: Material(
290 291 292
            type: MaterialType.transparency,
            textStyle: route.style,
            child: ScrollConfiguration(
293
              // Dropdown menus should never overscroll or display an overscroll indicator.
294
              // Scrollbars are built-in below.
295 296
              // Platform must use Theme and ScrollPhysics must be Clamping.
              behavior: ScrollConfiguration.of(context).copyWith(
297
                scrollbars: false,
298 299 300 301
                overscroll: false,
                physics: const ClampingScrollPhysics(),
                platform: Theme.of(context).platform,
              ),
302 303
              child: PrimaryScrollController(
                controller: widget.route.scrollController!,
304
                child: Scrollbar(
305
                  thumbVisibility: true,
306 307 308 309 310
                  child: ListView(
                    padding: kMaterialListPadding,
                    shrinkWrap: true,
                    children: children,
                  ),
311
                ),
312 313 314 315
              ),
            ),
          ),
        ),
316 317
      ),
    );
318 319 320
  }
}

321
class _DropdownMenuRouteLayout<T> extends SingleChildLayoutDelegate {
322
  _DropdownMenuRouteLayout({
323 324 325
    required this.buttonRect,
    required this.route,
    required this.textDirection,
326
  });
327

328
  final Rect buttonRect;
329
  final _DropdownRoute<T> route;
330
  final TextDirection? textDirection;
331 332 333

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
334 335 336
    // 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.
337
    //   -- https://material.io/design/components/menus.html#usage
338 339 340 341
    double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight);
    if (route.menuMaxHeight != null && route.menuMaxHeight! <= maxHeight) {
      maxHeight = route.menuMaxHeight!;
    }
342 343
    // 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.
344
    final double width = math.min(constraints.maxWidth, buttonRect.width);
345
    return BoxConstraints(
346 347
      minWidth: width,
      maxWidth: width,
348
      maxHeight: maxHeight,
349 350 351 352 353
    );
  }

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

356
    assert(() {
357
      final Rect container = Offset.zero & size;
358 359 360 361
      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.
362 363
        assert(menuLimits.top >= 0.0);
        assert(menuLimits.top + menuLimits.height <= size.height);
364 365
      }
      return true;
366
    }());
367
    assert(textDirection != null);
368
    final double left;
369
    switch (textDirection!) {
370
      case TextDirection.rtl:
371
        left = buttonRect.right.clamp(0.0, size.width) - childSize.width;
372 373
        break;
      case TextDirection.ltr:
374
        left = buttonRect.left.clamp(0.0, size.width - childSize.width);
375 376
        break;
    }
377 378

    return Offset(left, menuLimits.top);
379 380 381
  }

  @override
382
  bool shouldRelayout(_DropdownMenuRouteLayout<T> oldDelegate) {
383
    return buttonRect != oldDelegate.buttonRect || textDirection != oldDelegate.textDirection;
384
  }
385 386
}

387 388 389
// 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.
390
@immutable
391 392
class _DropdownRouteResult<T> {
  const _DropdownRouteResult(this.result);
393

394
  final T? result;
395 396

  @override
397
  bool operator ==(Object other) {
398 399
    return other is _DropdownRouteResult<T>
        && other.result == result;
400
  }
401 402

  @override
403 404 405
  int get hashCode => result.hashCode;
}

406 407 408 409 410 411 412 413
class _MenuLimits {
  const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset);
  final double top;
  final double bottom;
  final double height;
  final double scrollOffset;
}

414 415
class _DropdownRoute<T> extends PopupRoute<_DropdownRouteResult<T>> {
  _DropdownRoute({
416 417 418 419
    required this.items,
    required this.padding,
    required this.buttonRect,
    required this.selectedIndex,
420
    this.elevation = 8,
421
    required this.capturedThemes,
422
    required this.style,
423
    this.barrierLabel,
424
    this.itemHeight,
425
    this.dropdownColor,
426
    this.menuMaxHeight,
427
    required this.enableFeedback,
428
    this.borderRadius,
429 430
  }) : assert(style != null),
       itemHeights = List<double>.filled(items.length, itemHeight ?? kMinInteractiveDimension);
431

432
  final List<_MenuItem<T>> items;
433
  final EdgeInsetsGeometry padding;
434
  final Rect buttonRect;
Hixie's avatar
Hixie committed
435
  final int selectedIndex;
436
  final int elevation;
437
  final CapturedThemes capturedThemes;
438
  final TextStyle style;
439 440
  final double? itemHeight;
  final Color? dropdownColor;
441
  final double? menuMaxHeight;
442
  final bool enableFeedback;
443
  final BorderRadius? borderRadius;
444

445
  final List<double> itemHeights;
446
  ScrollController? scrollController;
447

448
  @override
449
  Duration get transitionDuration => _kDropdownMenuDuration;
450 451

  @override
452
  bool get barrierDismissible => true;
453 454

  @override
455
  Color? get barrierColor => null;
456

457
  @override
458
  final String? barrierLabel;
459

460
  @override
461
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
462 463 464 465 466 467 468 469 470 471
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return _DropdownRoutePage<T>(
          route: this,
          constraints: constraints,
          items: items,
          padding: padding,
          buttonRect: buttonRect,
          selectedIndex: selectedIndex,
          elevation: elevation,
472
          capturedThemes: capturedThemes,
473
          style: style,
474
          dropdownColor: dropdownColor,
475
          enableFeedback: enableFeedback,
476
          borderRadius: borderRadius,
477
        );
478
      },
479 480 481 482
    );
  }

  void _dismiss() {
483 484 485
    if (isActive) {
      navigator?.removeRoute(this);
    }
486 487
  }

488
  double getItemOffset(int index) {
489
    double offset = kMaterialListPadding.top;
490
    if (items.isNotEmpty && index > 0) {
491
      assert(items.length == itemHeights.length);
492
      offset += itemHeights
493
        .sublist(0, index)
494 495 496 497
        .reduce((double total, double height) => total + height);
    }
    return offset;
  }
498

499 500 501 502
  // 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.
503
  _MenuLimits getMenuLimits(Rect buttonRect, double availableHeight, int index) {
504 505 506 507
    double computedMaxHeight = availableHeight - 2.0 * _kMenuItemHeight;
    if (menuMaxHeight != null) {
      computedMaxHeight = math.min(computedMaxHeight, menuMaxHeight!);
    }
508
    final double buttonTop = buttonRect.top;
509
    final double buttonBottom = math.min(buttonRect.bottom, availableHeight);
510
    final double selectedItemOffset = getItemOffset(index);
511 512 513 514 515 516

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

519 520 521 522
    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);
523 524

    // If there are too many elements in the menu, we need to shrink it down
525 526
    // so it is at most the computedMaxHeight.
    final double menuHeight = math.min(computedMaxHeight, preferredMenuHeight);
527 528 529 530 531 532 533
    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.
534
    if (menuTop < topLimit) {
535
      menuTop = math.min(buttonTop, topLimit);
536 537
      menuBottom = menuTop + menuHeight;
    }
538

539 540 541
    if (menuBottom > bottomLimit) {
      menuBottom = math.max(buttonBottom, bottomLimit);
      menuTop = menuBottom - menuHeight;
542 543
    }

544 545 546 547 548
    if (menuBottom - itemHeights[selectedIndex] / 2.0 < buttonBottom - buttonRect.height / 2.0) {
      menuBottom = buttonBottom - buttonRect.height / 2.0 + itemHeights[selectedIndex] / 2.0;
      menuTop = menuBottom - menuHeight;
    }

549
    double scrollOffset = 0;
550 551 552 553 554 555
    // 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).
556
    if (preferredMenuHeight > computedMaxHeight) {
557 558 559 560 561 562 563
      // The offset should be zero if the selected item is in view at the beginning
      // of the menu. Otherwise, the scroll offset should center the item if possible.
      scrollOffset = math.max(0.0, selectedItemOffset - (buttonTop - menuTop));
      // If the selected item's scroll offset is greater than the maximum scroll offset,
      // set it instead to the maximum allowed scroll offset.
      scrollOffset = math.min(scrollOffset, preferredMenuHeight - menuHeight);
    }
564

565
    assert((menuBottom - menuTop - menuHeight).abs() < precisionErrorTolerance);
566 567 568 569 570 571
    return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset);
  }
}

class _DropdownRoutePage<T> extends StatelessWidget {
  const _DropdownRoutePage({
572 573 574
    Key? key,
    required this.route,
    required this.constraints,
575
    this.items,
576 577 578
    required this.padding,
    required this.buttonRect,
    required this.selectedIndex,
579
    this.elevation = 8,
580
    required this.capturedThemes,
581
    this.style,
582
    required this.dropdownColor,
583
    required this.enableFeedback,
584
    this.borderRadius,
585 586 587 588
  }) : super(key: key);

  final _DropdownRoute<T> route;
  final BoxConstraints constraints;
589
  final List<_MenuItem<T>>? items;
590 591 592
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final int selectedIndex;
593
  final int elevation;
594
  final CapturedThemes capturedThemes;
595 596
  final TextStyle? style;
  final Color? dropdownColor;
597
  final bool enableFeedback;
598
  final BorderRadius? borderRadius;
599 600 601 602 603 604 605 606 607 608

  @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
609
    // treating the items as if their heights were all equal to kMinInteractiveDimension.
610
    if (route.scrollController == null) {
611
      final _MenuLimits menuLimits = route.getMenuLimits(buttonRect, constraints.maxHeight, selectedIndex);
612
      route.scrollController = ScrollController(initialScrollOffset: menuLimits.scrollOffset);
613 614
    }

615
    final TextDirection? textDirection = Directionality.maybeOf(context);
616
    final Widget menu = _DropdownMenu<T>(
617
      route: route,
618
      padding: padding.resolve(textDirection),
619 620
      buttonRect: buttonRect,
      constraints: constraints,
621
      dropdownColor: dropdownColor,
622
      enableFeedback: enableFeedback,
623
      borderRadius: borderRadius,
624 625
    );

626
    return MediaQuery.removePadding(
627 628 629 630 631
      context: context,
      removeTop: true,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
632
      child: Builder(
633
        builder: (BuildContext context) {
634 635
          return CustomSingleChildLayout(
            delegate: _DropdownMenuRouteLayout<T>(
636
              buttonRect: buttonRect,
637
              route: route,
638
              textDirection: textDirection,
639
            ),
640
            child: capturedThemes.wrap(menu),
641 642
          );
        },
643
      ),
644
    );
645
  }
646 647
}

648 649 650 651
// 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,
652
// as closely as possible.
653 654
class _MenuItem<T> extends SingleChildRenderObjectWidget {
  const _MenuItem({
655 656 657
    Key? key,
    required this.onLayout,
    required this.item,
658 659 660
  }) : assert(onLayout != null), super(key: key, child: item);

  final ValueChanged<Size> onLayout;
661
  final DropdownMenuItem<T>? item;
662 663 664 665 666 667 668 669 670 671 672 673 674

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

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

class _RenderMenuItem extends RenderProxyBox {
675
  _RenderMenuItem(this.onLayout, [RenderBox? child]) : assert(onLayout != null), super(child);
676 677 678 679 680 681 682 683 684 685

  ValueChanged<Size> onLayout;

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

686 687 688 689
// 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 {
690
  /// Creates an item for a dropdown menu.
691 692
  ///
  /// The [child] argument is required.
693
  const _DropdownMenuItemContainer({
694
    Key? key,
695
    this.alignment = AlignmentDirectional.centerStart,
696
    required this.child,
697 698
  }) : assert(child != null),
       super(key: key);
699

700
  /// The widget below this widget in the tree.
701 702
  ///
  /// Typically a [Text] widget.
703
  final Widget child;
704

705 706 707 708 709 710 711 712 713 714 715 716
  /// Defines how the item is positioned within the container.
  ///
  /// This property must not be null. It defaults to [AlignmentDirectional.centerStart].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
  final AlignmentGeometry alignment;

717
  @override
718
  Widget build(BuildContext context) {
719
    return Container(
720
      constraints: const BoxConstraints(minHeight: _kMenuItemHeight),
721
      alignment: alignment,
722
      child: child,
723 724 725 726
    );
  }
}

727 728 729 730 731 732 733 734 735
/// 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({
736
    Key? key,
737
    this.onTap,
738
    this.value,
739
    this.enabled = true,
740
    AlignmentGeometry alignment = AlignmentDirectional.centerStart,
741
    required Widget child,
742
  }) : assert(child != null),
743
       super(key: key, alignment:alignment, child: child);
744

745
  /// Called when the dropdown menu item is tapped.
746
  final VoidCallback? onTap;
747

748 749 750
  /// The value to return if the user selects this menu item.
  ///
  /// Eventually returned in a call to [DropdownButton.onChanged].
751
  final T? value;
752 753 754 755 756

  /// Whether or not a user can select this menu item.
  ///
  /// Defaults to `true`.
  final bool enabled;
757 758
}

759
/// An inherited widget that causes any descendant [DropdownButton]
760 761 762
/// widgets to not include their regular underline.
///
/// This is used by [DataTable] to remove the underline from any
763
/// [DropdownButton] widgets placed within material data tables, as
764
/// required by the material design specification.
765 766
class DropdownButtonHideUnderline extends InheritedWidget {
  /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must
767
  /// be given.
768
  const DropdownButtonHideUnderline({
769 770
    Key? key,
    required Widget child,
771 772
  }) : assert(child != null),
       super(key: key, child: child);
773

774
  /// Returns whether the underline of [DropdownButton] widgets should
775 776
  /// be hidden.
  static bool at(BuildContext context) {
777
    return context.dependOnInheritedWidgetOfExactType<DropdownButtonHideUnderline>() != null;
778 779 780
  }

  @override
781
  bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false;
782 783
}

784 785 786 787 788 789
/// 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.
///
790 791 792
/// One ancestor must be a [Material] widget and typically this is
/// provided by the app's [Scaffold].
///
793 794
/// 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.
795 796 797
/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be
/// specialized with that same type argument.
///
798 799 800 801
/// 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.
///
802
/// {@tool dartpad}
803 804 805
/// 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".
806
///
807
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png)
808
///
809
/// ** See code in examples/api/lib/material/dropdown/dropdown_button.0.dart **
810 811 812 813 814
/// {@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
815 816 817
/// 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.
818
///
819 820 821
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
822
///
823
///  * [DropdownButtonFormField], which integrates with the [Form] widget.
824
///  * [DropdownMenuItem], the class used to represent the [items].
825
///  * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons
826
///    from displaying their underlines.
827
///  * [ElevatedButton], [TextButton], ordinary buttons that trigger a single action.
828
///  * <https://material.io/design/components/menus.html#dropdown-menu>
829
class DropdownButton<T> extends StatefulWidget {
830
  /// Creates a dropdown button.
831
  ///
832
  /// The [items] must have distinct values. If [value] isn't null then it
833
  /// must be equal to one of the [DropdownMenuItem] values. If [items] or
834
  /// [onChanged] is null, the button will be disabled, the down arrow
835 836 837 838 839 840 841 842
  /// will be greyed out.
  ///
  /// If [value] is null and the button is enabled, [hint] will be displayed
  /// if it is non-null.
  ///
  /// If [value] is null and the button is disabled, [disabledHint] will be displayed
  /// if it is non-null. If [disabledHint] is null, then [hint] will be displayed
  /// if it is non-null.
843 844
  ///
  /// The [elevation] and [iconSize] arguments must not be null (they both have
845 846
  /// defaults, so do not need to be specified). The boolean [isDense] and
  /// [isExpanded] arguments must not be null.
847
  ///
848 849
  /// The [autofocus] argument must not be null.
  ///
850 851 852
  /// 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.
853
  DropdownButton({
854 855
    Key? key,
    required this.items,
856
    this.selectedItemBuilder,
857
    this.value,
858
    this.hint,
859
    this.disabledHint,
860
    required this.onChanged,
861
    this.onTap,
862
    this.elevation = 8,
863
    this.style,
864
    this.underline,
865 866 867
    this.icon,
    this.iconDisabledColor,
    this.iconEnabledColor,
868 869
    this.iconSize = 24.0,
    this.isDense = false,
870
    this.isExpanded = false,
871
    this.itemHeight = kMinInteractiveDimension,
872 873 874
    this.focusColor,
    this.focusNode,
    this.autofocus = false,
875
    this.dropdownColor,
876
    this.menuMaxHeight,
877
    this.enableFeedback,
878
    this.alignment = AlignmentDirectional.centerStart,
879
    this.borderRadius,
880 881
    // When adding new arguments, consider adding similar arguments to
    // DropdownButtonFormField.
882 883 884 885
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
886
                "There should be exactly one item with [DropdownButton]'s value: "
887 888 889 890
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
891 892 893 894
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
895
       assert(autofocus != null),
896
       assert(itemHeight == null || itemHeight >=  kMinInteractiveDimension),
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
       _inputDecoration = null,
       _isEmpty = false,
       _isFocused = false,
       super(key: key);

  DropdownButton._formField({
    Key? key,
    required this.items,
    this.selectedItemBuilder,
    this.value,
    this.hint,
    this.disabledHint,
    required this.onChanged,
    this.onTap,
    this.elevation = 8,
    this.style,
    this.underline,
    this.icon,
    this.iconDisabledColor,
    this.iconEnabledColor,
    this.iconSize = 24.0,
    this.isDense = false,
    this.isExpanded = false,
    this.itemHeight = kMinInteractiveDimension,
    this.focusColor,
    this.focusNode,
    this.autofocus = false,
    this.dropdownColor,
    this.menuMaxHeight,
    this.enableFeedback,
    this.alignment = AlignmentDirectional.centerStart,
    this.borderRadius,
    required InputDecoration inputDecoration,
    required bool isEmpty,
    required bool isFocused,
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
                "There should be exactly one item with [DropdownButtonFormField]'s value: "
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
       assert(autofocus != null),
       assert(itemHeight == null || itemHeight >=  kMinInteractiveDimension),
       assert(isEmpty != null),
       assert(isFocused != null),
       _inputDecoration = inputDecoration,
       _isEmpty = isEmpty,
       _isFocused = isFocused,
952
       super(key: key);
953

954 955 956 957
  /// 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
958
  /// displayed in grey and it will not respond to input.
959
  final List<DropdownMenuItem<T>>? items;
960

961 962
  /// The value of the currently selected [DropdownMenuItem].
  ///
963 964 965 966 967 968
  /// If [value] is null and the button is enabled, [hint] will be displayed
  /// if it is non-null.
  ///
  /// If [value] is null and the button is disabled, [disabledHint] will be displayed
  /// if it is non-null. If [disabledHint] is null, then [hint] will be displayed
  /// if it is non-null.
969
  final T? value;
970

971 972
  /// A placeholder widget that is displayed by the dropdown button.
  ///
973 974 975 976 977
  /// If [value] is null and the dropdown is enabled ([items] and [onChanged] are non-null),
  /// this widget is displayed as a placeholder for the dropdown button's value.
  ///
  /// If [value] is null and the dropdown is disabled and [disabledHint] is null,
  /// this widget is used as the placeholder.
978
  final Widget? hint;
979

980
  /// A preferred placeholder widget that is displayed when the dropdown is disabled.
981
  ///
982 983
  /// If [value] is null, the dropdown is disabled ([items] or [onChanged] is null),
  /// this widget is displayed as a placeholder for the dropdown button's value.
984
  final Widget? disabledHint;
985

986
  /// {@template flutter.material.dropdownButton.onChanged}
987
  /// Called when the user selects an item.
988
  ///
989 990
  /// 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
991
  /// displayed in grey and it will not respond to input. A disabled button
992 993 994
  /// 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.
995
  /// {@endtemplate}
996
  final ValueChanged<T?>? onChanged;
997

998 999 1000 1001 1002 1003
  /// 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.
1004
  final VoidCallback? onTap;
1005

1006 1007 1008 1009 1010 1011 1012
  /// 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].
  ///
1013
  /// {@tool dartpad}
1014 1015 1016
  /// This sample shows a `DropdownButton` with a button with [Text] that
  /// corresponds to but is unique from [DropdownMenuItem].
  ///
1017
  /// ** See code in examples/api/lib/material/dropdown/dropdown_button.selected_item_builder.0.dart **
1018 1019 1020 1021
  /// {@end-tool}
  ///
  /// If this callback is null, the [DropdownMenuItem] from [items]
  /// that matches [value] will be displayed.
1022
  final DropdownButtonBuilder? selectedItemBuilder;
1023

1024
  /// The z-coordinate at which to place the menu when open.
1025 1026 1027 1028
  ///
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12,
  /// 16, and 24. See [kElevationToShadow].
  ///
1029
  /// Defaults to 8, the appropriate elevation for dropdown buttons.
1030
  final int elevation;
1031

1032
  /// The text style to use for text in the dropdown button and the dropdown
1033 1034
  /// menu that appears when you tap the button.
  ///
1035
  /// To use a separate text style for selected item when it's displayed within
1036
  /// the dropdown button, consider using [selectedItemBuilder].
1037
  ///
1038
  /// {@tool dartpad}
1039 1040 1041
  /// This sample shows a `DropdownButton` with a dropdown button text style
  /// that is different than its menu items.
  ///
1042
  /// ** See code in examples/api/lib/material/dropdown/dropdown_button.style.0.dart **
1043 1044
  /// {@end-tool}
  ///
1045
  /// Defaults to the [TextTheme.subtitle1] value of the current
1046
  /// [ThemeData.textTheme] of the current [Theme].
1047
  final TextStyle? style;
1048

1049 1050 1051
  /// The widget to use for drawing the drop-down button's underline.
  ///
  /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD.
1052
  final Widget? underline;
1053

1054 1055 1056
  /// The widget to use for the drop-down button's icon.
  ///
  /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph.
1057
  final Widget? icon;
1058 1059 1060 1061

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

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

1075 1076
  /// The size to use for the drop-down button's down arrow icon button.
  ///
1077
  /// Defaults to 24.0.
1078 1079
  final double iconSize;

1080 1081 1082 1083 1084
  /// 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
1085
  /// its own decorations, like [InputDecorator].
1086 1087
  final bool isDense;

1088 1089 1090 1091 1092 1093 1094
  /// 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;

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  /// 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].
1106
  final double? itemHeight;
1107

1108
  /// The color for the button's [Material] when it has the input focus.
1109
  final Color? focusColor;
1110 1111

  /// {@macro flutter.widgets.Focus.focusNode}
1112
  final FocusNode? focusNode;
1113 1114 1115 1116

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

1117 1118 1119 1120
  /// The background color of the dropdown.
  ///
  /// If it is not provided, the theme's [ThemeData.canvasColor] will be used
  /// instead.
1121
  final Color? dropdownColor;
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
  /// The maximum height of the menu.
  ///
  /// The maximum height of the menu must be at least one row shorter than
  /// the height of the app's view. This ensures that a tappable area
  /// outside of the simple menu is present so the user can dismiss the menu.
  ///
  /// If this property is set above the maximum allowable height threshold
  /// mentioned above, then the menu defaults to being padded at the top
  /// and bottom of the menu by at one menu item's height.
  final double? menuMaxHeight;

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
  /// Whether detected gestures should provide acoustic and/or haptic feedback.
  ///
  /// For example, on Android a tap will produce a clicking sound and a
  /// long-press will produce a short vibration, when feedback is enabled.
  ///
  /// By default, platform-specific feedback is enabled.
  ///
  /// See also:
  ///
  ///  * [Feedback] for providing platform-specific feedback to certain actions.
  final bool? enableFeedback;

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
  /// Defines how the hint or the selected item is positioned within the button.
  ///
  /// This property must not be null. It defaults to [AlignmentDirectional.centerStart].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
  final AlignmentGeometry alignment;

1158 1159 1160
  /// Defines the corner radii of the menu's rounded rectangle shape.
  final BorderRadius? borderRadius;

1161 1162 1163 1164 1165 1166
  final InputDecoration? _inputDecoration;

  final bool _isEmpty;

  final bool _isFocused;

1167
  @override
1168
  State<DropdownButton<T>> createState() => _DropdownButtonState<T>();
1169 1170
}

1171
class _DropdownButtonState<T> extends State<DropdownButton<T>> with WidgetsBindingObserver {
1172 1173 1174 1175 1176
  int? _selectedIndex;
  _DropdownRoute<T>? _dropdownRoute;
  Orientation? _lastOrientation;
  FocusNode? _internalNode;
  FocusNode? get focusNode => widget.focusNode ?? _internalNode;
1177
  bool _hasPrimaryFocus = false;
1178
  late Map<Type, Action<Intent>> _actionMap;
1179 1180 1181 1182 1183

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

1185
  @override
1186 1187 1188
  void initState() {
    super.initState();
    _updateSelectedIndex();
1189 1190 1191
    if (widget.focusNode == null) {
      _internalNode ??= _createFocusNode();
    }
1192 1193 1194 1195
    _actionMap = <Type, Action<Intent>>{
      ActivateIntent: CallbackAction<ActivateIntent>(
        onInvoke: (ActivateIntent intent) => _handleTap(),
      ),
1196 1197 1198
      ButtonActivateIntent: CallbackAction<ButtonActivateIntent>(
        onInvoke: (ButtonActivateIntent intent) => _handleTap(),
      ),
1199
    };
1200
    focusNode!.addListener(_handleFocusChanged);
1201 1202
  }

1203 1204
  @override
  void dispose() {
1205
    WidgetsBinding.instance.removeObserver(this);
1206
    _removeDropdownRoute();
1207
    focusNode!.removeListener(_handleFocusChanged);
1208
    _internalNode?.dispose();
1209 1210 1211
    super.dispose();
  }

1212 1213
  void _removeDropdownRoute() {
    _dropdownRoute?._dismiss();
1214
    _dropdownRoute = null;
1215
    _lastOrientation = null;
1216 1217
  }

1218
  void _handleFocusChanged() {
1219
    if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) {
1220
      setState(() {
1221
        _hasPrimaryFocus = focusNode!.hasPrimaryFocus;
1222 1223 1224 1225
      });
    }
  }

1226

1227
  @override
1228
  void didUpdateWidget(DropdownButton<T> oldWidget) {
1229
    super.didUpdateWidget(oldWidget);
1230 1231 1232 1233 1234
    if (widget.focusNode != oldWidget.focusNode) {
      oldWidget.focusNode?.removeListener(_handleFocusChanged);
      if (widget.focusNode == null) {
        _internalNode ??= _createFocusNode();
      }
1235 1236
      _hasPrimaryFocus = focusNode!.hasPrimaryFocus;
      focusNode!.addListener(_handleFocusChanged);
1237
    }
1238
    _updateSelectedIndex();
1239 1240 1241
  }

  void _updateSelectedIndex() {
1242 1243 1244 1245
    if (widget.items == null
        || widget.items!.isEmpty
        || (widget.value == null &&
            widget.items!
1246
                .where((DropdownMenuItem<T> item) => item.enabled && item.value == widget.value)
1247
                .isEmpty)) {
1248
      _selectedIndex = null;
1249 1250 1251
      return;
    }

1252
    assert(widget.items!.where((DropdownMenuItem<T> item) => item.value == widget.value).length == 1);
1253 1254
    for (int itemIndex = 0; itemIndex < widget.items!.length; itemIndex++) {
      if (widget.items![itemIndex].value == widget.value) {
1255 1256 1257 1258 1259 1260
        _selectedIndex = itemIndex;
        return;
      }
    }
  }

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

1263
  void _handleTap() {
1264
    final TextDirection? textDirection = Directionality.maybeOf(context);
1265
    final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown
1266
      ? _kAlignedMenuMargin
1267
      : _kUnalignedMenuMargin;
1268

1269 1270 1271 1272
    final List<_MenuItem<T>> menuItems = <_MenuItem<T>>[
    for (int index = 0; index < widget.items!.length; index += 1)
      _MenuItem<T>(
        item: widget.items![index],
1273
        onLayout: (Size size) {
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
          // 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;

1285
          _dropdownRoute!.itemHeights[index] = size.height;
1286
        },
1287
      ),
1288
    ];
1289

1290
    final NavigatorState navigator = Navigator.of(context);
1291
    assert(_dropdownRoute == null);
1292 1293
    final RenderBox itemBox = context.findRenderObject()! as RenderBox;
    final Rect itemRect = itemBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject()) & itemBox.size;
1294
    _dropdownRoute = _DropdownRoute<T>(
1295
      items: menuItems,
1296 1297
      buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect),
      padding: _kMenuItemPadding.resolve(textDirection),
1298
      selectedIndex: _selectedIndex ?? 0,
1299
      elevation: widget.elevation,
1300
      capturedThemes: InheritedTheme.capture(from: context, to: navigator.context),
1301
      style: _textStyle!,
1302
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
1303
      itemHeight: widget.itemHeight,
1304
      dropdownColor: widget.dropdownColor,
1305
      menuMaxHeight: widget.menuMaxHeight,
1306
      enableFeedback: widget.enableFeedback ?? true,
1307
      borderRadius: widget.borderRadius,
1308 1309
    );

1310
    focusNode?.requestFocus();
1311
    navigator.push(_dropdownRoute!).then<void>((_DropdownRouteResult<T>? newValue) {
1312
      _removeDropdownRoute();
1313
      if (!mounted || newValue == null)
1314
        return;
1315
      widget.onChanged?.call(newValue.result);
1316
    });
1317

1318
    widget.onTap?.call();
1319 1320
  }

1321 1322 1323 1324 1325
  // 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 {
1326
    final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.subtitle1!.fontSize!;
1327
    return math.max(fontSize, math.max(widget.iconSize, _kDenseButtonHeight));
1328 1329
  }

1330
  Color get _iconColor {
1331 1332
    // These colors are not defined in the Material Design spec.
    if (_enabled) {
1333
      if (widget.iconEnabledColor != null)
1334
        return widget.iconEnabledColor!;
1335

1336
      switch (Theme.of(context).brightness) {
1337 1338 1339 1340
        case Brightness.light:
          return Colors.grey.shade700;
        case Brightness.dark:
          return Colors.white70;
1341 1342
      }
    } else {
1343
      if (widget.iconDisabledColor != null)
1344
        return widget.iconDisabledColor!;
1345

1346
      switch (Theme.of(context).brightness) {
1347 1348 1349 1350
        case Brightness.light:
          return Colors.grey.shade400;
        case Brightness.dark:
          return Colors.white10;
1351 1352 1353 1354
      }
    }
  }

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

1357
  Orientation _getOrientation(BuildContext context) {
1358
    Orientation? result = MediaQuery.maybeOf(context)?.orientation;
1359 1360 1361
    if (result == null) {
      // If there's no MediaQuery, then use the window aspect to determine
      // orientation.
1362
      final Size size = WidgetsBinding.instance.window.physicalSize;
1363 1364 1365 1366 1367
      result = size.width > size.height ? Orientation.landscape : Orientation.portrait;
    }
    return result;
  }

1368
  @override
1369
  Widget build(BuildContext context) {
1370
    assert(debugCheckHasMaterial(context));
1371
    assert(debugCheckHasMaterialLocalizations(context));
1372 1373 1374 1375 1376 1377
    final Orientation newOrientation = _getOrientation(context);
    _lastOrientation ??= newOrientation;
    if (newOrientation != _lastOrientation) {
      _removeDropdownRoute();
      _lastOrientation = newOrientation;
    }
1378 1379 1380

    // The width of the button and the menu are defined by the widest
    // item and the width of the hint.
1381 1382 1383 1384
    // 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
1385 1386
      ? (widget.items != null ? List<Widget>.of(widget.items!) : <Widget>[])
      : List<Widget>.of(widget.selectedItemBuilder!(context));
1387

1388
    int? hintIndex;
1389
    if (widget.hint != null || (!_enabled && widget.disabledHint != null)) {
1390
      Widget displayedHint = _enabled ? widget.hint! : widget.disabledHint ?? widget.hint!;
1391 1392 1393
      if (widget.selectedItemBuilder == null)
        displayedHint = _DropdownMenuItemContainer(child: displayedHint);

1394
      hintIndex = items.length;
1395
      items.add(DefaultTextStyle(
1396
        style: _textStyle!.copyWith(color: Theme.of(context).hintColor),
1397
        child: IgnorePointer(
1398
          ignoringSemantics: false,
1399
          child: displayedHint,
1400 1401 1402 1403
        ),
      ));
    }

1404 1405 1406 1407
    final EdgeInsetsGeometry padding = ButtonTheme.of(context).alignedDropdown
      ? _kAlignedButtonPadding
      : _kUnalignedButtonPadding;

1408
    // If value is null (then _selectedIndex is null) then we
1409
    // display the hint or nothing at all.
1410
    final Widget innerItemsWidget;
1411 1412 1413 1414
    if (items.isEmpty) {
      innerItemsWidget = Container();
    } else {
      innerItemsWidget = IndexedStack(
1415
        index: _selectedIndex ?? hintIndex,
1416
        alignment: widget.alignment,
1417 1418 1419 1420 1421
        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(),
1422 1423
      );
    }
1424

1425 1426
    const Icon defaultIcon = Icon(Icons.arrow_drop_down);

1427
    Widget result = DefaultTextStyle(
1428
      style: _enabled ? _textStyle! : _textStyle!.copyWith(color: Theme.of(context).disabledColor),
1429
      child: Container(
1430
        padding: padding.resolve(Directionality.of(context)),
1431
        height: widget.isDense ? _denseButtonHeight : null,
1432
        child: Row(
1433 1434 1435
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
1436 1437 1438 1439
            if (widget.isExpanded)
              Expanded(child: innerItemsWidget)
            else
              innerItemsWidget,
1440 1441 1442 1443 1444 1445
            IconTheme(
              data: IconThemeData(
                color: _iconColor,
                size: widget.iconSize,
              ),
              child: widget.icon ?? defaultIcon,
1446 1447 1448 1449
            ),
          ],
        ),
      ),
1450
    );
1451

1452
    if (!DropdownButtonHideUnderline.at(context)) {
1453
      final double bottom = (widget.isDense || widget.itemHeight == null) ? 0.0 : 8.0;
1454
      result = Stack(
1455 1456
        children: <Widget>[
          result,
1457
          Positioned(
1458 1459
            left: 0.0,
            right: 0.0,
1460
            bottom: bottom,
1461
            child: widget.underline ?? Container(
1462 1463
              height: 1.0,
              decoration: const BoxDecoration(
1464 1465 1466 1467 1468 1469
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFBDBDBD),
                    width: 0.0,
                  ),
                ),
1470 1471 1472 1473
              ),
            ),
          ),
        ],
1474 1475
      );
    }
1476

1477 1478 1479 1480 1481 1482 1483
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
      MaterialStateMouseCursor.clickable,
      <MaterialState>{
        if (!_enabled) MaterialState.disabled,
      },
    );

1484 1485 1486 1487 1488 1489 1490 1491 1492
    if (widget._inputDecoration != null) {
      result = InputDecorator(
        decoration: widget._inputDecoration!,
        isEmpty: widget._isEmpty,
        isFocused: widget._isFocused,
        child: result,
      );
    }

1493
    return Semantics(
1494
      button: true,
1495 1496
      child: Actions(
        actions: _actionMap,
1497 1498 1499
        child: InkWell(
          mouseCursor: effectiveMouseCursor,
          onTap: _enabled ? _handleTap : null,
1500 1501 1502
          canRequestFocus: _enabled,
          focusNode: focusNode,
          autofocus: widget.autofocus,
1503 1504 1505
          focusColor: widget.focusColor ?? Theme.of(context).focusColor,
          enableFeedback: false,
          child: result,
1506
        ),
1507
      ),
1508 1509 1510
    );
  }
}
1511

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
/// A [FormField] that contains a [DropdownButton].
///
/// This is a convenience widget that wraps a [DropdownButton] widget in a
/// [FormField].
///
/// A [Form] ancestor is not required. The [Form] simply makes it easier to
/// save, reset, or validate multiple fields at once. To use without a [Form],
/// pass a [GlobalKey] to the constructor and use [GlobalKey.currentState] to
/// save or reset the form field.
///
/// See also:
///
///  * [DropdownButton], which is the underlying text field without the [Form]
///    integration.
1526
class DropdownButtonFormField<T> extends FormField<T> {
1527 1528 1529
  /// Creates a [DropdownButton] widget that is a [FormField], wrapped in an
  /// [InputDecorator].
  ///
1530
  /// For a description of the `onSaved`, `validator`, or `autovalidateMode`
1531 1532
  /// parameters, see [FormField]. For the rest (other than [decoration]), see
  /// [DropdownButton].
1533
  ///
1534 1535
  /// The `items`, `elevation`, `iconSize`, `isDense`, `isExpanded`,
  /// `autofocus`, and `decoration`  parameters must not be null.
1536
  DropdownButtonFormField({
1537 1538 1539 1540 1541 1542
    Key? key,
    required List<DropdownMenuItem<T>>? items,
    DropdownButtonBuilder? selectedItemBuilder,
    T? value,
    Widget? hint,
    Widget? disabledHint,
1543
    required this.onChanged,
1544
    VoidCallback? onTap,
1545
    int elevation = 8,
1546 1547 1548 1549
    TextStyle? style,
    Widget? icon,
    Color? iconDisabledColor,
    Color? iconEnabledColor,
1550
    double iconSize = 24.0,
1551
    bool isDense = true,
1552
    bool isExpanded = false,
1553 1554 1555
    double? itemHeight,
    Color? focusColor,
    FocusNode? focusNode,
1556
    bool autofocus = false,
1557 1558 1559 1560 1561
    Color? dropdownColor,
    InputDecoration? decoration,
    FormFieldSetter<T>? onSaved,
    FormFieldValidator<T>? validator,
    AutovalidateMode? autovalidateMode,
1562
    double? menuMaxHeight,
1563 1564
    bool? enableFeedback,
    AlignmentGeometry alignment = AlignmentDirectional.centerStart,
1565 1566 1567
    BorderRadius? borderRadius,
    // When adding new arguments, consider adding similar arguments to
    // DropdownButton.
1568 1569 1570 1571
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
1572
                "There should be exactly one item with [DropdownButton]'s value: "
1573 1574 1575 1576
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
1577 1578 1579 1580
       assert(elevation != null),
       assert(iconSize != null),
       assert(isDense != null),
       assert(isExpanded != null),
1581 1582 1583
       assert(itemHeight == null || itemHeight >= kMinInteractiveDimension),
       assert(autofocus != null),
       decoration = decoration ?? InputDecoration(focusColor: focusColor),
1584 1585 1586 1587 1588
       super(
         key: key,
         onSaved: onSaved,
         initialValue: value,
         validator: validator,
1589
         autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled,
1590
         builder: (FormFieldState<T> field) {
1591
           final _DropdownButtonFormFieldState<T> state = field as _DropdownButtonFormFieldState<T>;
1592 1593
           final InputDecoration decorationArg =  decoration ?? InputDecoration(focusColor: focusColor);
           final InputDecoration effectiveDecoration = decorationArg.applyDefaults(
1594
             Theme.of(field.context).inputDecorationTheme,
1595
           );
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607

           final bool showSelectedItem = items != null && items.where((DropdownMenuItem<T> item) => item.value == state.value).isNotEmpty;
           bool isHintOrDisabledHintAvailable() {
             final bool isDropdownDisabled = onChanged == null || (items == null || items.isEmpty);
             if (isDropdownDisabled) {
               return hint != null || disabledHint != null;
             } else {
               return hint != null;
             }
           }
           final bool isEmpty = !showSelectedItem && !isHintOrDisabledHintAvailable();

1608 1609 1610 1611 1612 1613
           // 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) {
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
               return DropdownButtonHideUnderline(
                 child: DropdownButton<T>._formField(
                   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,
                   menuMaxHeight: menuMaxHeight,
                   enableFeedback: enableFeedback,
                   alignment: alignment,
                   borderRadius: borderRadius,
                   inputDecoration: effectiveDecoration.copyWith(errorText: field.errorText),
                   isEmpty: isEmpty,
                   isFocused: Focus.of(context).hasFocus,
1643 1644 1645
                 ),
               );
             }),
1646
           );
1647
         },
1648 1649
       );

1650
  /// {@macro flutter.material.dropdownButton.onChanged}
1651
  final ValueChanged<T?>? onChanged;
1652

1653 1654
  /// The decoration to show around the dropdown button form field.
  ///
1655 1656
  /// 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.
1657
  ///
1658 1659
  /// If not specified, an [InputDecorator] with the `focusColor` set to the
  /// supplied `focusColor` (if any) will be used.
1660 1661
  final InputDecoration decoration;

1662 1663 1664 1665 1666 1667 1668
  @override
  FormFieldState<T> createState() => _DropdownButtonFormFieldState<T>();
}

class _DropdownButtonFormFieldState<T> extends FormFieldState<T> {

  @override
1669
  void didChange(T? value) {
1670
    super.didChange(value);
1671 1672 1673
    final DropdownButtonFormField<T> dropdownButtonFormField = widget as DropdownButtonFormField<T>;
    assert(dropdownButtonFormField.onChanged != null);
    dropdownButtonFormField.onChanged!(value);
1674
  }
1675 1676 1677 1678 1679 1680 1681 1682

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