dropdown.dart 59.2 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: clampDouble(selectedItemOffset, 0.0, math.max(size.height - _kMenuItemHeight, 0.0)),
71
      end: 0.0,
72 73
    );

74
    final Tween<double> bottom = Tween<double>(
75
      begin: clampDouble(top.begin! + _kMenuItemHeight, 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
    super.key,
98 99 100 101 102
    this.padding,
    required this.route,
    required this.buttonRect,
    required this.constraints,
    required this.itemIndex,
103
    required this.enableFeedback,
104
  });
105 106

  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
    switch (FocusManager.instance.highlightMode) {
      case FocusHighlightMode.touch:
        inTraditionalMode = false;
      case FocusHighlightMode.traditional:
        inTraditionalMode = true;
    }

    if (focused && inTraditionalMode) {
      final _MenuLimits menuLimits = widget.route.getMenuLimits(
129 130 131 132
        widget.buttonRect,
        widget.constraints.maxHeight,
        widget.itemIndex,
      );
133
      widget.route.scrollController!.animateTo(
134 135 136 137 138 139 140 141
        menuLimits.scrollOffset,
        curve: Curves.easeInOut,
        duration: const Duration(milliseconds: 100),
      );
    }
  }

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

144
    dropdownMenuItem.onTap?.call();
145

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

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

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

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

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

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

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

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

244
  @override
245 246
  Widget build(BuildContext context) {
    // The menu is shown in three stages (unit timing in brackets):
Hixie's avatar
Hixie committed
247 248
    // [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
249
    //   until it's big enough for as many items as we're going to show.
Hixie's avatar
Hixie committed
250
    // [0.5s - 1.0s] Fade in the remaining visible items from top to bottom.
251 252
    //
    // When the menu is dismissed we just fade the entire thing out
Hixie's avatar
Hixie committed
253
    // in the first 0.25s.
254
    assert(debugCheckHasMaterialLocalizations(context));
255
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
256
    final _DropdownRoute<T> route = widget.route;
257 258 259 260 261 262 263 264
    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,
265
          enableFeedback: widget.enableFeedback,
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
          borderRadius: widget.borderRadius,
278 279
          // This offset is passed as a callback, not a value, because it must
          // be retrieved at paint time (after layout), not at build time.
280
          getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex),
281
        ),
282
        child: Semantics(
283 284 285 286
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
          child: ClipRRect(
            borderRadius: widget.borderRadius ?? BorderRadius.zero,
            clipBehavior: widget.borderRadius != null
              ? Clip.antiAlias
              : Clip.none,
            child: Material(
              type: MaterialType.transparency,
              textStyle: route.style,
              child: ScrollConfiguration(
                // Dropdown menus should never overscroll or display an overscroll indicator.
                // Scrollbars are built-in below.
                // Platform must use Theme and ScrollPhysics must be Clamping.
                behavior: ScrollConfiguration.of(context).copyWith(
                  scrollbars: false,
                  overscroll: false,
                  physics: const ClampingScrollPhysics(),
                  platform: Theme.of(context).platform,
                ),
                child: PrimaryScrollController(
                  controller: widget.route.scrollController!,
                  child: Scrollbar(
                    thumbVisibility: true,
                    child: ListView(
310 311
                      // Ensure this always inherits the PrimaryScrollController
                      primary: true,
312 313 314 315
                      padding: kMaterialListPadding,
                      shrinkWrap: true,
                      children: children,
                    ),
316
                  ),
317
                ),
318 319 320 321
              ),
            ),
          ),
        ),
322 323
      ),
    );
324 325 326
  }
}

327
class _DropdownMenuRouteLayout<T> extends SingleChildLayoutDelegate {
328
  _DropdownMenuRouteLayout({
329 330 331
    required this.buttonRect,
    required this.route,
    required this.textDirection,
332
  });
333

334
  final Rect buttonRect;
335
  final _DropdownRoute<T> route;
336
  final TextDirection? textDirection;
337 338 339

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

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

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

    return Offset(left, menuLimits.top);
383 384 385
  }

  @override
386
  bool shouldRelayout(_DropdownMenuRouteLayout<T> oldDelegate) {
387
    return buttonRect != oldDelegate.buttonRect || textDirection != oldDelegate.textDirection;
388
  }
389 390
}

391 392 393
// 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.
394
@immutable
395 396
class _DropdownRouteResult<T> {
  const _DropdownRouteResult(this.result);
397

398
  final T? result;
399 400

  @override
401
  bool operator ==(Object other) {
402 403
    return other is _DropdownRouteResult<T>
        && other.result == result;
404
  }
405 406

  @override
407 408 409
  int get hashCode => result.hashCode;
}

410 411 412 413 414 415 416 417
class _MenuLimits {
  const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset);
  final double top;
  final double bottom;
  final double height;
  final double scrollOffset;
}

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

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

448
  final List<double> itemHeights;
449
  ScrollController? scrollController;
450

451
  @override
452
  Duration get transitionDuration => _kDropdownMenuDuration;
453 454

  @override
455
  bool get barrierDismissible => true;
456 457

  @override
458
  Color? get barrierColor => null;
459

460
  @override
461
  final String? barrierLabel;
462

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

  void _dismiss() {
486 487 488
    if (isActive) {
      navigator?.removeRoute(this);
    }
489 490
  }

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

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

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

522 523
    double menuTop = (buttonTop - selectedItemOffset) - (itemHeights[selectedIndex] - buttonRect.height) / 2.0;
    double preferredMenuHeight = kMaterialListPadding.vertical;
524
    if (items.isNotEmpty) {
525
      preferredMenuHeight += itemHeights.reduce((double total, double height) => total + height);
526
    }
527 528

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

543 544 545
    if (menuBottom > bottomLimit) {
      menuBottom = math.max(buttonBottom, bottomLimit);
      menuTop = menuBottom - menuHeight;
546 547
    }

548 549 550 551 552
    if (menuBottom - itemHeights[selectedIndex] / 2.0 < buttonBottom - buttonRect.height / 2.0) {
      menuBottom = buttonBottom - buttonRect.height / 2.0 + itemHeights[selectedIndex] / 2.0;
      menuTop = menuBottom - menuHeight;
    }

553
    double scrollOffset = 0;
554 555 556 557 558 559
    // 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).
560
    if (preferredMenuHeight > computedMaxHeight) {
561 562 563 564 565 566 567
      // 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);
    }
568

569
    assert((menuBottom - menuTop - menuHeight).abs() < precisionErrorTolerance);
570 571 572 573 574 575
    return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset);
  }
}

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

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

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

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

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

652 653 654 655
// 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,
656
// as closely as possible.
657 658
class _MenuItem<T> extends SingleChildRenderObjectWidget {
  const _MenuItem({
659
    super.key,
660 661
    required this.onLayout,
    required this.item,
662
  }) : super(child: item);
663 664

  final ValueChanged<Size> onLayout;
665
  final DropdownMenuItem<T>? item;
666 667 668 669 670 671 672 673 674 675 676 677 678

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

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

class _RenderMenuItem extends RenderProxyBox {
679
  _RenderMenuItem(this.onLayout, [RenderBox? child]) : super(child);
680 681 682 683 684 685 686 687 688 689

  ValueChanged<Size> onLayout;

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

690 691 692 693
// 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 {
694
  /// Creates an item for a dropdown menu.
695 696
  ///
  /// The [child] argument is required.
697
  const _DropdownMenuItemContainer({
698
    super.key,
699
    this.alignment = AlignmentDirectional.centerStart,
700
    required this.child,
701
  });
702

703
  /// The widget below this widget in the tree.
704 705
  ///
  /// Typically a [Text] widget.
706
  final Widget child;
707

708 709 710 711 712 713 714 715 716 717 718 719
  /// 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;

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

730 731 732 733 734 735 736 737 738
/// 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({
739
    super.key,
740
    this.onTap,
741
    this.value,
742
    this.enabled = true,
743 744
    super.alignment,
    required super.child,
745
  });
746

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

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

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

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

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

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

785
/// A Material Design button for selecting from a list of items.
786 787 788 789 790
///
/// 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.
///
791 792
/// {@youtube 560 315 https://www.youtube.com/watch?v=ZzQ_PWrFihg}
///
793 794 795
/// One ancestor must be a [Material] widget and typically this is
/// provided by the app's [Scaffold].
///
796 797
/// 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.
798 799 800
/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be
/// specialized with that same type argument.
///
801 802 803 804
/// 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.
///
805
/// {@tool dartpad}
806
/// This sample shows a [DropdownButton] with a large arrow icon,
807 808
/// purple text style, and bold purple underline, whose value is one of "One",
/// "Two", "Free", or "Four".
809
///
810
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png)
811
///
812
/// ** See code in examples/api/lib/material/dropdown/dropdown_button.0.dart **
813 814 815 816 817
/// {@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
818 819 820
/// 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.
821
///
822 823
/// Requires one of its ancestors to be a [Material] widget.
///
824 825
/// {@youtube 560 315 https://www.youtube.com/watch?v=ZzQ_PWrFihg}
///
826
/// See also:
827
///
828
///  * [DropdownButtonFormField], which integrates with the [Form] widget.
829
///  * [DropdownMenuItem], the class used to represent the [items].
830
///  * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons
831
///    from displaying their underlines.
832
///  * [ElevatedButton], [TextButton], ordinary buttons that trigger a single action.
833
///  * <https://material.io/design/components/menus.html#dropdown-menu>
834
class DropdownButton<T> extends StatefulWidget {
835
  /// Creates a dropdown button.
836
  ///
837
  /// The [items] must have distinct values. If [value] isn't null then it
838
  /// must be equal to one of the [DropdownMenuItem] values. If [items] or
839
  /// [onChanged] is null, the button will be disabled, the down arrow
840 841 842 843 844 845 846 847
  /// 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.
848 849
  ///
  /// The [elevation] and [iconSize] arguments must not be null (they both have
850 851
  /// defaults, so do not need to be specified). The boolean [isDense] and
  /// [isExpanded] arguments must not be null.
852
  ///
853 854
  /// The [autofocus] argument must not be null.
  ///
855 856 857
  /// 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.
858
  DropdownButton({
859
    super.key,
860
    required this.items,
861
    this.selectedItemBuilder,
862
    this.value,
863
    this.hint,
864
    this.disabledHint,
865
    required this.onChanged,
866
    this.onTap,
867
    this.elevation = 8,
868
    this.style,
869
    this.underline,
870 871 872
    this.icon,
    this.iconDisabledColor,
    this.iconEnabledColor,
873 874
    this.iconSize = 24.0,
    this.isDense = false,
875
    this.isExpanded = false,
876
    this.itemHeight = kMinInteractiveDimension,
877 878 879
    this.focusColor,
    this.focusNode,
    this.autofocus = false,
880
    this.dropdownColor,
881
    this.menuMaxHeight,
882
    this.enableFeedback,
883
    this.alignment = AlignmentDirectional.centerStart,
884
    this.borderRadius,
885
    this.padding,
886 887
    // When adding new arguments, consider adding similar arguments to
    // DropdownButtonFormField.
888 889 890 891
  }) : assert(items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1,
892
                "There should be exactly one item with [DropdownButton]'s value: "
893 894 895 896
                '$value. \n'
                'Either zero or 2 or more [DropdownMenuItem]s were detected '
                'with the same value',
              ),
897
       assert(itemHeight == null || itemHeight >=  kMinInteractiveDimension),
898 899
       _inputDecoration = null,
       _isEmpty = false,
900
       _isFocused = false;
901 902

  DropdownButton._formField({
903
    super.key,
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
    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,
929
    this.padding,
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
    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(itemHeight == null || itemHeight >=  kMinInteractiveDimension),
       _inputDecoration = inputDecoration,
       _isEmpty = isEmpty,
945
       _isFocused = isFocused;
946

947 948 949 950
  /// 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
951
  /// displayed in grey and it will not respond to input.
952
  final List<DropdownMenuItem<T>>? items;
953

954 955
  /// The value of the currently selected [DropdownMenuItem].
  ///
956 957 958 959 960 961
  /// 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.
962
  final T? value;
963

964 965
  /// A placeholder widget that is displayed by the dropdown button.
  ///
966 967 968 969 970
  /// 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.
971
  final Widget? hint;
972

973
  /// A preferred placeholder widget that is displayed when the dropdown is disabled.
974
  ///
975 976
  /// 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.
977
  final Widget? disabledHint;
978

979
  /// {@template flutter.material.dropdownButton.onChanged}
980
  /// Called when the user selects an item.
981
  ///
982 983
  /// 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
984
  /// displayed in grey and it will not respond to input. A disabled button
985 986 987
  /// 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.
988
  /// {@endtemplate}
989
  final ValueChanged<T?>? onChanged;
990

991 992 993 994 995 996
  /// 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.
997
  final VoidCallback? onTap;
998

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

1017
  /// The z-coordinate at which to place the menu when open.
1018 1019 1020 1021
  ///
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12,
  /// 16, and 24. See [kElevationToShadow].
  ///
1022
  /// Defaults to 8, the appropriate elevation for dropdown buttons.
1023
  final int elevation;
1024

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

1042 1043 1044
  /// The widget to use for drawing the drop-down button's underline.
  ///
  /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD.
1045
  final Widget? underline;
1046

1047 1048 1049
  /// The widget to use for the drop-down button's icon.
  ///
  /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph.
1050
  final Widget? icon;
1051 1052 1053 1054

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

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

1068 1069
  /// The size to use for the drop-down button's down arrow icon button.
  ///
1070
  /// Defaults to 24.0.
1071 1072
  final double iconSize;

1073 1074 1075 1076 1077
  /// 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
1078
  /// its own decorations, like [InputDecorator].
1079 1080
  final bool isDense;

1081 1082 1083 1084 1085 1086 1087
  /// 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;

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  /// 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].
1099
  final double? itemHeight;
1100

1101
  /// The color for the button's [Material] when it has the input focus.
1102
  final Color? focusColor;
1103 1104

  /// {@macro flutter.widgets.Focus.focusNode}
1105
  final FocusNode? focusNode;
1106 1107 1108 1109

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

1110 1111 1112 1113
  /// The background color of the dropdown.
  ///
  /// If it is not provided, the theme's [ThemeData.canvasColor] will be used
  /// instead.
1114
  final Color? dropdownColor;
1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  /// Padding around the visible portion of the dropdown widget.
  ///
  /// As the padding increases, the size of the [DropdownButton] will also
  /// increase. The padding is included in the clickable area of the dropdown
  /// widget, so this can make the widget easier to click.
  ///
  /// Padding can be useful when used with a custom border. The clickable
  /// area will stay flush with the border, as opposed to an external [Padding]
  /// widget which will leave a non-clickable gap.
  final EdgeInsetsGeometry? padding;

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  /// 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;

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
  /// 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;

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  /// 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;

1162 1163 1164
  /// Defines the corner radii of the menu's rounded rectangle shape.
  final BorderRadius? borderRadius;

1165 1166 1167 1168 1169 1170
  final InputDecoration? _inputDecoration;

  final bool _isEmpty;

  final bool _isFocused;

1171
  @override
1172
  State<DropdownButton<T>> createState() => _DropdownButtonState<T>();
1173 1174
}

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

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

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

1207 1208
  @override
  void dispose() {
1209
    WidgetsBinding.instance.removeObserver(this);
1210
    _removeDropdownRoute();
1211
    focusNode!.removeListener(_handleFocusChanged);
1212
    _internalNode?.dispose();
1213 1214 1215
    super.dispose();
  }

1216 1217
  void _removeDropdownRoute() {
    _dropdownRoute?._dismiss();
1218
    _dropdownRoute = null;
1219
    _lastOrientation = null;
1220 1221
  }

1222
  void _handleFocusChanged() {
1223
    if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) {
1224
      setState(() {
1225
        _hasPrimaryFocus = focusNode!.hasPrimaryFocus;
1226 1227 1228 1229
      });
    }
  }

1230

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

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

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

1265
  TextStyle? get _textStyle => widget.style ?? Theme.of(context).textTheme.titleMedium;
1266

1267
  void _handleTap() {
1268
    final TextDirection? textDirection = Directionality.maybeOf(context);
1269
    final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown
1270
      ? _kAlignedMenuMargin
1271
      : _kUnalignedMenuMargin;
1272

1273 1274 1275 1276
    final List<_MenuItem<T>> menuItems = <_MenuItem<T>>[
    for (int index = 0; index < widget.items!.length; index += 1)
      _MenuItem<T>(
        item: widget.items![index],
1277
        onLayout: (Size size) {
1278 1279 1280 1281 1282 1283 1284 1285
          // 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.
1286
          if (_dropdownRoute == null) {
1287
            return;
1288
          }
1289

1290
          _dropdownRoute!.itemHeights[index] = size.height;
1291
        },
1292
      ),
1293
    ];
1294

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

1315
    focusNode?.requestFocus();
1316
    navigator.push(_dropdownRoute!).then<void>((_DropdownRouteResult<T>? newValue) {
1317
      _removeDropdownRoute();
1318
      if (!mounted || newValue == null) {
1319
        return;
1320
      }
1321
      widget.onChanged?.call(newValue.result);
1322
    });
1323

1324
    widget.onTap?.call();
1325 1326
  }

1327 1328 1329 1330 1331
  // 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 {
1332
    final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
1333
    final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!;
1334 1335
    final double scaledFontSize = textScaleFactor * fontSize;
    return math.max(scaledFontSize, math.max(widget.iconSize, _kDenseButtonHeight));
1336 1337
  }

1338
  Color get _iconColor {
1339 1340
    // These colors are not defined in the Material Design spec.
    if (_enabled) {
1341
      if (widget.iconEnabledColor != null) {
1342
        return widget.iconEnabledColor!;
1343
      }
1344

1345
      switch (Theme.of(context).brightness) {
1346 1347 1348 1349
        case Brightness.light:
          return Colors.grey.shade700;
        case Brightness.dark:
          return Colors.white70;
1350 1351
      }
    } else {
1352
      if (widget.iconDisabledColor != null) {
1353
        return widget.iconDisabledColor!;
1354
      }
1355

1356
      switch (Theme.of(context).brightness) {
1357 1358 1359 1360
        case Brightness.light:
          return Colors.grey.shade400;
        case Brightness.dark:
          return Colors.white10;
1361 1362 1363 1364
      }
    }
  }

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

1367
  Orientation _getOrientation(BuildContext context) {
1368
    Orientation? result = MediaQuery.maybeOrientationOf(context);
1369
    if (result == null) {
1370
      // If there's no MediaQuery, then use the view aspect to determine
1371
      // orientation.
1372
      final Size size = View.of(context).physicalSize;
1373 1374 1375 1376 1377
      result = size.width > size.height ? Orientation.landscape : Orientation.portrait;
    }
    return result;
  }

1378
  @override
1379
  Widget build(BuildContext context) {
1380
    assert(debugCheckHasMaterial(context));
1381
    assert(debugCheckHasMaterialLocalizations(context));
1382 1383 1384 1385 1386 1387
    final Orientation newOrientation = _getOrientation(context);
    _lastOrientation ??= newOrientation;
    if (newOrientation != _lastOrientation) {
      _removeDropdownRoute();
      _lastOrientation = newOrientation;
    }
1388 1389 1390

    // The width of the button and the menu are defined by the widest
    // item and the width of the hint.
1391 1392 1393 1394
    // 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
1395 1396
      ? (widget.items != null ? List<Widget>.of(widget.items!) : <Widget>[])
      : List<Widget>.of(widget.selectedItemBuilder!(context));
1397

1398
    int? hintIndex;
1399
    if (widget.hint != null || (!_enabled && widget.disabledHint != null)) {
1400
      final Widget displayedHint = _enabled ? widget.hint! : widget.disabledHint ?? widget.hint!;
1401

1402
      hintIndex = items.length;
1403
      items.add(DefaultTextStyle(
1404
        style: _textStyle!.copyWith(color: Theme.of(context).hintColor),
1405
        child: IgnorePointer(
1406 1407 1408 1409
          child: _DropdownMenuItemContainer(
            alignment: widget.alignment,
            child: displayedHint,
          ),
1410 1411 1412 1413
        ),
      ));
    }

1414 1415 1416 1417
    final EdgeInsetsGeometry padding = ButtonTheme.of(context).alignedDropdown
      ? _kAlignedButtonPadding
      : _kUnalignedButtonPadding;

1418
    // If value is null (then _selectedIndex is null) then we
1419
    // display the hint or nothing at all.
1420
    final Widget innerItemsWidget;
1421
    if (items.isEmpty) {
1422
      innerItemsWidget = const SizedBox.shrink();
1423 1424
    } else {
      innerItemsWidget = IndexedStack(
1425
        index: _selectedIndex ?? hintIndex,
1426
        alignment: widget.alignment,
1427 1428 1429 1430 1431
        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(),
1432 1433
      );
    }
1434

1435 1436
    const Icon defaultIcon = Icon(Icons.arrow_drop_down);

1437
    Widget result = DefaultTextStyle(
1438
      style: _enabled ? _textStyle! : _textStyle!.copyWith(color: Theme.of(context).disabledColor),
1439
      child: Container(
1440
        padding: padding.resolve(Directionality.of(context)),
1441
        height: widget.isDense ? _denseButtonHeight : null,
1442
        child: Row(
1443 1444 1445
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
1446 1447 1448 1449
            if (widget.isExpanded)
              Expanded(child: innerItemsWidget)
            else
              innerItemsWidget,
1450 1451 1452 1453 1454 1455
            IconTheme(
              data: IconThemeData(
                color: _iconColor,
                size: widget.iconSize,
              ),
              child: widget.icon ?? defaultIcon,
1456 1457 1458 1459
            ),
          ],
        ),
      ),
1460
    );
1461

1462
    if (!DropdownButtonHideUnderline.at(context)) {
1463
      final double bottom = (widget.isDense || widget.itemHeight == null) ? 0.0 : 8.0;
1464
      result = Stack(
1465 1466
        children: <Widget>[
          result,
1467
          Positioned(
1468 1469
            left: 0.0,
            right: 0.0,
1470
            bottom: bottom,
1471
            child: widget.underline ?? Container(
1472 1473
              height: 1.0,
              decoration: const BoxDecoration(
1474 1475 1476 1477 1478 1479
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFBDBDBD),
                    width: 0.0,
                  ),
                ),
1480 1481 1482 1483
              ),
            ),
          ),
        ],
1484 1485
      );
    }
1486

1487 1488 1489 1490 1491 1492 1493
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
      MaterialStateMouseCursor.clickable,
      <MaterialState>{
        if (!_enabled) MaterialState.disabled,
      },
    );

1494 1495 1496 1497 1498 1499 1500 1501 1502
    if (widget._inputDecoration != null) {
      result = InputDecorator(
        decoration: widget._inputDecoration!,
        isEmpty: widget._isEmpty,
        isFocused: widget._isFocused,
        child: result,
      );
    }

1503
    return Semantics(
1504
      button: true,
1505 1506
      child: Actions(
        actions: _actionMap,
1507 1508 1509
        child: InkWell(
          mouseCursor: effectiveMouseCursor,
          onTap: _enabled ? _handleTap : null,
1510
          canRequestFocus: _enabled,
1511
          borderRadius: widget.borderRadius,
1512 1513
          focusNode: focusNode,
          autofocus: widget.autofocus,
1514 1515
          focusColor: widget.focusColor ?? Theme.of(context).focusColor,
          enableFeedback: false,
1516
          child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result),
1517
        ),
1518
      ),
1519 1520 1521
    );
  }
}
1522

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

           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();

1612 1613 1614 1615 1616 1617
           // 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) {
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 1643 1644 1645 1646
               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,
1647
                   padding: padding,
1648 1649 1650
                 ),
               );
             }),
1651
           );
1652
         },
1653 1654
       );

1655
  /// {@macro flutter.material.dropdownButton.onChanged}
1656
  final ValueChanged<T?>? onChanged;
1657

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

1667 1668 1669 1670 1671 1672 1673
  @override
  FormFieldState<T> createState() => _DropdownButtonFormFieldState<T>();
}

class _DropdownButtonFormFieldState<T> extends FormFieldState<T> {

  @override
1674
  void didChange(T? value) {
1675
    super.didChange(value);
1676 1677 1678
    final DropdownButtonFormField<T> dropdownButtonFormField = widget as DropdownButtonFormField<T>;
    assert(dropdownButtonFormField.onChanged != null);
    dropdownButtonFormField.onChanged!(value);
1679
  }
1680 1681 1682 1683 1684 1685 1686 1687

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