dropdown_form_field_test.dart 34.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;

import 'package:flutter/material.dart';
8
import 'package:flutter_test/flutter_test.dart';
9 10 11 12

import '../rendering/mock_canvas.dart';

const List<String> menuItems = <String>['one', 'two', 'three', 'four'];
13
void onChanged<T>(T _) { }
14 15 16 17
final Type dropdownButtonType = DropdownButton<String>(
  onChanged: (_) { },
  items: const <DropdownMenuItem<String>>[],
).runtimeType;
18 19 20 21 22 23 24 25 26

Finder _iconRichText(Key iconKey) {
  return find.descendant(
    of: find.byKey(iconKey),
    matching: find.byType(RichText),
  );
}

Widget buildFormFrame({
27
  Key? buttonKey,
28
  AutovalidateMode autovalidateMode = AutovalidateMode.disabled,
29
  int elevation = 8,
30 31 32 33 34 35
  String? value = 'two',
  ValueChanged<String?>? onChanged,
  VoidCallback? onTap,
  Widget? icon,
  Color? iconDisabledColor,
  Color? iconEnabledColor,
36
  double iconSize = 24.0,
37
  bool isDense = true,
38
  bool isExpanded = false,
39 40 41 42
  Widget? hint,
  Widget? disabledHint,
  Widget? underline,
  List<String>? items = menuItems,
43 44
  Alignment alignment = Alignment.center,
  TextDirection textDirection = TextDirection.ltr,
45
  AlignmentGeometry buttonAlignment = AlignmentDirectional.centerStart,
46 47 48 49 50 51 52 53 54
}) {
  return TestApp(
    textDirection: textDirection,
    child: Material(
      child: Align(
        alignment: alignment,
        child: RepaintBoundary(
          child: DropdownButtonFormField<String>(
            key: buttonKey,
55
            autovalidateMode: autovalidateMode,
56 57 58 59 60
            elevation: elevation,
            value: value,
            hint: hint,
            disabledHint: disabledHint,
            onChanged: onChanged,
61
            onTap: onTap,
62 63 64 65 66 67
            icon: icon,
            iconSize: iconSize,
            iconDisabledColor: iconDisabledColor,
            iconEnabledColor: iconEnabledColor,
            isDense: isDense,
            isExpanded: isExpanded,
68
            items: items?.map<DropdownMenuItem<String>>((String item) {
69 70 71
              return DropdownMenuItem<String>(
                key: ValueKey<String>(item),
                value: item,
72
                child: Text(item, key: ValueKey<String>('${item}Text')),
73 74
              );
            }).toList(),
75
            alignment: buttonAlignment,
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
          ),
        ),
      ),
    ),
  );
}

class _TestAppState extends State<TestApp> {
  @override
  Widget build(BuildContext context) {
    return Localizations(
      locale: const Locale('en', 'US'),
      delegates: const <LocalizationsDelegate<dynamic>>[
        DefaultWidgetsLocalizations.delegate,
        DefaultMaterialLocalizations.delegate,
      ],
      child: MediaQuery(
93
        data: MediaQueryData.fromWindow(WidgetsBinding.instance.window).copyWith(size: widget.mediaSize),
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        child: Directionality(
          textDirection: widget.textDirection,
          child: Navigator(
            onGenerateRoute: (RouteSettings settings) {
              assert(settings.name == '/');
              return MaterialPageRoute<void>(
                settings: settings,
                builder: (BuildContext context) => widget.child,
              );
            },
          ),
        ),
      ),
    );
  }
}

class TestApp extends StatefulWidget {
112
  const TestApp({
113
    super.key,
114 115
    required this.textDirection,
    required this.child,
116
    this.mediaSize,
117
  });
118

119 120
  final TextDirection textDirection;
  final Widget child;
121
  final Size? mediaSize;
122

123
  @override
124
  State<TestApp> createState() => _TestAppState();
125 126
}

127
void verifyPaintedShadow(Finder customPaint, int elevation) {
128 129
  const Rect originalRectangle = Rect.fromLTRB(0.0, 0.0, 800, 208.0);

130
  final List<BoxShadow> boxShadows = List<BoxShadow>.generate(3, (int index) => kElevationToShadow[elevation]![index]);
131 132 133
  final List<RRect> rrects = List<RRect>.generate(3, (int index) {
    return RRect.fromRectAndRadius(
      originalRectangle.shift(
134
        boxShadows[index].offset,
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
      ).inflate(boxShadows[index].spreadRadius),
      const Radius.circular(2.0),
    );
  });

  expect(
    customPaint,
    paints
      ..save()
      ..rrect(rrect: rrects[0], color: boxShadows[0].color, hasMaskFilter: true)
      ..rrect(rrect: rrects[1], color: boxShadows[1].color, hasMaskFilter: true)
      ..rrect(rrect: rrects[2], color: boxShadows[2].color, hasMaskFilter: true),
  );
}

void main() {
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  // Regression test for https://github.com/flutter/flutter/issues/87102
  testWidgets('label position test - show hint', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            hint: const Text('Hint'),
            onChanged: (int? newValue) {
              value = newValue;
            },
            items: const <DropdownMenuItem<int?>>[
              DropdownMenuItem<int?>(
                value: 1,
                child: Text('One'),
              ),
              DropdownMenuItem<int?>(
                value: 2,
                child: Text('Two'),
              ),
              DropdownMenuItem<int?>(
                value: 3,
                child: Text('Three'),
              ),
            ],
          ),
        ),
      ),
    );

    expect(value, null);
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));

    // Select a item.
    await tester.tap(find.text('Hint'), warnIfMissed: false);
    await tester.pumpAndSettle();
    await tester.tap(find.text('One').last);
    await tester.pumpAndSettle();

    expect(value, 1);
    final Offset oneValueLabel = tester.getTopLeft(find.text('labelText'));

    // The position of the label does not change.
    expect(hintEmptyLabel, oneValueLabel);
  });

  testWidgets('label position test - show disabledHint: disable', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
215
            onChanged: null, // this disables the menu and shows the disabledHint.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
            disabledHint: const Text('disabledHint'),
            items: const <DropdownMenuItem<int?>>[
              DropdownMenuItem<int?>(
                value: 1,
                child: Text('One'),
              ),
              DropdownMenuItem<int?>(
                value: 2,
                child: Text('Two'),
              ),
              DropdownMenuItem<int?>(
                value: 3,
                child: Text('Three'),
              ),
            ],
          ),
        ),
      ),
    );

    expect(value, null); // disabledHint shown.
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 12.0));
  });

  testWidgets('label position test - show disabledHint: enable + null item', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            disabledHint: const Text('disabledHint'),
            onChanged: (_) {},
            items: null,
          ),
        ),
      ),
    );

    expect(value, null); // disabledHint shown.
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 12.0));
  });

  testWidgets('label position test - show disabledHint: enable + empty item', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            disabledHint: const Text('disabledHint'),
            onChanged: (_) {},
            items: const <DropdownMenuItem<int?>>[],
          ),
        ),
      ),
    );

    expect(value, null); // disabledHint shown.
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 12.0));
  });

  testWidgets('label position test - show hint: enable + empty item', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            hint: const Text('hint'),
            onChanged: (_) {},
            items: const <DropdownMenuItem<int?>>[],
          ),
        ),
      ),
    );

    expect(value, null); // hint shown.
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 12.0));
  });

  testWidgets('label position test - no hint shown: enable + no selected + disabledHint', (WidgetTester tester) async {
    int? value;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            disabledHint: const Text('disabledHint'),
            onChanged: (_) {},
            items: const <DropdownMenuItem<int?>>[
              DropdownMenuItem<int?>(
                value: 1,
                child: Text('One'),
              ),
              DropdownMenuItem<int?>(
                value: 2,
                child: Text('Two'),
              ),
              DropdownMenuItem<int?>(
                value: 3,
                child: Text('Three'),
              ),
            ],
          ),
        ),
      ),
    );

    expect(value, null);
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 24.0));
  });

  testWidgets('label position test - show selected item: disabled + hint + disabledHint', (WidgetTester tester) async {
    const int value = 1;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            hint: const Text('hint'),
367
            onChanged: null, // disabled
368
            disabledHint: const Text('disabledHint'),
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            items: const <DropdownMenuItem<int?>>[
              DropdownMenuItem<int?>(
                value: 1,
                child: Text('One'),
              ),
              DropdownMenuItem<int?>(
                value: 2,
                child: Text('Two'),
              ),
              DropdownMenuItem<int?>(
                value: 3,
                child: Text('Three'),
              ),
            ],
          ),
        ),
      ),
    );

    expect(value, 1);
    final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
    expect(hintEmptyLabel, const Offset(0.0, 12.0));
  });

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
  // Regression test for https://github.com/flutter/flutter/issues/82910
  testWidgets('null value test', (WidgetTester tester) async {
    int? value = 1;

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<int?>(
            decoration: const InputDecoration(
              labelText: 'labelText',
            ),
            value: value,
            onChanged: (int? newValue) {
              value = newValue;
            },
            items: const <DropdownMenuItem<int?>>[
              DropdownMenuItem<int?>(
                child: Text('None'),
              ),
              DropdownMenuItem<int?>(
                value: 1,
                child: Text('One'),
              ),
              DropdownMenuItem<int?>(
                value: 2,
                child: Text('Two'),
              ),
              DropdownMenuItem<int?>(
                value: 3,
                child: Text('Three'),
424
              ),
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
            ],
          ),
        ),
      ),
    );

    expect(value, 1);
    final Offset nonEmptyLabel = tester.getTopLeft(find.text('labelText'));

    // Switch to `null` value item from value 1.
    await tester.tap(find.text('One'));
    await tester.pumpAndSettle();
    await tester.tap(find.text('None').last);
    await tester.pump();

    expect(value, null);
    final Offset nullValueLabel = tester.getTopLeft(find.text('labelText'));
    // The position of the label does not change.
    expect(nonEmptyLabel, nullValueLabel);
  });

446
  testWidgets('DropdownButtonFormField with autovalidation test', (WidgetTester tester) async {
447
    String? value = 'one';
448
    int validateCalled = 0;
449 450 451 452 453 454 455 456 457 458

    await tester.pumpWidget(
      StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return MaterialApp(
            home: Material(
              child: DropdownButtonFormField<String>(
                value: value,
                hint: const Text('Select Value'),
                decoration: const InputDecoration(
459
                  prefixIcon: Icon(Icons.fastfood),
460 461 462 463 464 465 466
                ),
                items: menuItems.map((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
467
                onChanged: (String? newValue) {
468 469 470 471
                  setState(() {
                    value = newValue;
                  });
                },
472
                validator: (String? currentValue) {
473
                  validateCalled++;
474 475
                  return currentValue == null ? 'Must select value' : null;
                },
476
                autovalidateMode: AutovalidateMode.always,
477 478 479 480 481 482 483
              ),
            ),
          );
        },
      ),
    );

484
    expect(validateCalled, 1);
485 486 487 488 489
    expect(value, equals('one'));
    await tester.tap(find.text('one'));
    await tester.pumpAndSettle();
    await tester.tap(find.text('three').last);
    await tester.pump();
490
    expect(validateCalled, 2);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    await tester.pumpAndSettle();
    expect(value, equals('three'));
  });

  testWidgets('DropdownButtonFormField arrow icon aligns with the edge of button when expanded', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

    // There shouldn't be overflow when expanded although list contains longer items.
    final List<String> items = <String>[
      '1234567890',
      'abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890',
    ];

    await tester.pumpWidget(
      buildFormFrame(
        buttonKey: buttonKey,
        value: '1234567890',
        isExpanded: true,
        onChanged: onChanged,
        items: items,
      ),
    );
    final RenderBox buttonBox = tester.renderObject<RenderBox>(
      find.byKey(buttonKey),
    );
    expect(buttonBox.attached, isTrue);

    final RenderBox arrowIcon = tester.renderObject<RenderBox>(
      find.byIcon(Icons.arrow_drop_down),
    );
    expect(arrowIcon.attached, isTrue);

    // Arrow icon should be aligned with far right of button when expanded
    expect(
      arrowIcon.localToGlobal(Offset.zero).dx,
      buttonBox.size.centerRight(Offset(-arrowIcon.size.width, 0.0)).dx,
    );
  });

  testWidgets('DropdownButtonFormField with isDense:true aligns selected menu item', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

    await tester.pumpWidget(
      buildFormFrame(
        buttonKey: buttonKey,
        onChanged: onChanged,
      ),
    );
    final RenderBox buttonBox = tester.renderObject<RenderBox>(
      find.byKey(buttonKey),
    );
    expect(buttonBox.attached, isTrue);

    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1)); // finish the menu animation

    // The selected dropdown item is both in menu we just popped up, and in
    // the IndexedStack contained by the dropdown button. Both of them should
    // have the same vertical center as the button.
    final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(
      find.byKey(const ValueKey<String>('two')),
    ).toList();
    expect(itemBoxes.length, equals(2));

    // When isDense is true, the button's height is reduced. The menu items'
    // heights are not.
    final List<double> itemBoxesHeight = itemBoxes.map<double>((RenderBox box) => box.size.height).toList();
    final double menuItemHeight = itemBoxesHeight.reduce(math.max);
    expect(menuItemHeight, greaterThanOrEqualTo(buttonBox.size.height));

562
    for (final RenderBox itemBox in itemBoxes) {
563 564 565 566 567 568 569
      expect(itemBox.attached, isTrue);
      final Offset buttonBoxCenter = buttonBox.size.center(buttonBox.localToGlobal(Offset.zero));
      final Offset itemBoxCenter = itemBox.size.center(itemBox.localToGlobal(Offset.zero));
      expect(buttonBoxCenter.dy, equals(itemBoxCenter.dy));
    }
  });

570 571 572 573 574 575 576 577 578
  testWidgets('DropdownButtonFormField.isDense is true by default', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/46844
    final Key buttonKey = UniqueKey();
    const String value = 'two';

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
579 580 581 582 583 584 585 586 587 588 589 590 591
          child: Center(
            child: DropdownButtonFormField<String>(
              key: buttonKey,
              value: value,
              onChanged: onChanged,
              items: menuItems.map<DropdownMenuItem<String>>((String item) {
                return DropdownMenuItem<String>(
                  key: ValueKey<String>(item),
                  value: item,
                  child: Text(item, key: ValueKey<String>('${item}Text')),
                );
              }).toList(),
            ),
592 593 594 595 596 597
          ),
        ),
      ),
    );

    final RenderBox box = tester.renderObject<RenderBox>(find.byType(dropdownButtonType));
598
    expect(box.size.height, 48.0);
599 600
  });

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  testWidgets('DropdownButtonFormField - custom text style', (WidgetTester tester) async {
    const String value = 'foo';
    final UniqueKey itemKey = UniqueKey();

    await tester.pumpWidget(
      TestApp(
        textDirection: TextDirection.ltr,
        child: Material(
          child: DropdownButtonFormField<String>(
            value: value,
            items: <DropdownMenuItem<String>>[
              DropdownMenuItem<String>(
                key: itemKey,
                value: 'foo',
                child: const Text(value),
              ),
            ],
            onChanged: (_) { },
            style: const TextStyle(
              color: Colors.amber,
              fontSize: 20.0,
            ),
          ),
        ),
      ),
    );

    final RichText richText = tester.widget<RichText>(
      find.descendant(
        of: find.byKey(itemKey),
        matching: find.byType(RichText),
      ),
    );

635 636
    expect(richText.text.style!.color, Colors.amber);
    expect(richText.text.style!.fontSize, 20.0);
637 638 639 640 641
  });

  testWidgets('DropdownButtonFormField - disabledHint displays when the items list is empty, when items is null', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

642
    Widget build({ List<String>? items }) {
643 644 645 646 647 648 649 650 651
      return buildFormFrame(
        items: items,
        buttonKey: buttonKey,
        value: null,
        hint: const Text('enabled'),
        disabledHint: const Text('disabled'),
      );
    }
    // [disabledHint] should display when [items] is null
652
    await tester.pumpWidget(build());
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    expect(find.text('enabled'), findsNothing);
    expect(find.text('disabled'), findsOneWidget);

    // [disabledHint] should display when [items] is an empty list.
    await tester.pumpWidget(build(items: <String>[]));
    expect(find.text('enabled'), findsNothing);
    expect(find.text('disabled'), findsOneWidget);
  });

  testWidgets(
    'DropdownButtonFormField - hint displays when the items list is '
    'empty, items is null, and disabledHint is null',
    (WidgetTester tester) async {
      final Key buttonKey = UniqueKey();

668
      Widget build({ List<String>? items }) {
669 670 671 672 673 674 675 676
        return buildFormFrame(
          items: items,
          buttonKey: buttonKey,
          value: null,
          hint: const Text('hint used when disabled'),
        );
      }
      // [hint] should display when [items] is null and [disabledHint] is not defined
677
      await tester.pumpWidget(build());
678 679 680 681 682 683 684 685 686 687 688
      expect(find.text('hint used when disabled'), findsOneWidget);

      // [hint] should display when [items] is an empty list and [disabledHint] is not defined.
      await tester.pumpWidget(build(items: <String>[]));
      expect(find.text('hint used when disabled'), findsOneWidget);
    },
  );

  testWidgets('DropdownButtonFormField - disabledHint is null by default', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

689
    Widget build({ List<String>? items }) {
690 691 692 693 694 695 696 697
      return buildFormFrame(
        items: items,
        buttonKey: buttonKey,
        value: null,
        hint: const Text('hint used when disabled'),
      );
    }
    // [hint] should display when [items] is null and [disabledHint] is not defined
698
    await tester.pumpWidget(build());
699 700 701 702 703 704 705 706 707 708
    expect(find.text('hint used when disabled'), findsOneWidget);

    // [hint] should display when [items] is an empty list and [disabledHint] is not defined.
    await tester.pumpWidget(build(items: <String>[]));
    expect(find.text('hint used when disabled'), findsOneWidget);
  });

  testWidgets('DropdownButtonFormField - disabledHint is null by default', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

709
    Widget build({ List<String>? items }) {
710 711 712 713 714 715 716 717
      return buildFormFrame(
        items: items,
        buttonKey: buttonKey,
        value: null,
        hint: const Text('hint used when disabled'),
      );
    }
    // [hint] should display when [items] is null and [disabledHint] is not defined
718
    await tester.pumpWidget(build());
719 720 721 722 723 724 725 726 727 728
    expect(find.text('hint used when disabled'), findsOneWidget);

    // [hint] should display when [items] is an empty list and [disabledHint] is not defined.
    await tester.pumpWidget(build(items: <String>[]));
    expect(find.text('hint used when disabled'), findsOneWidget);
  });

  testWidgets('DropdownButtonFormField - disabledHint displays when onChanged is null', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

729
    Widget build({ List<String>? items, ValueChanged<String?>? onChanged }) {
730 731 732 733 734 735 736 737 738
      return buildFormFrame(
        items: items,
        buttonKey: buttonKey,
        value: null,
        onChanged: onChanged,
        hint: const Text('enabled'),
        disabledHint: const Text('disabled'),
      );
    }
739
    await tester.pumpWidget(build(items: menuItems));
740 741 742 743 744 745 746
    expect(find.text('enabled'), findsNothing);
    expect(find.text('disabled'), findsOneWidget);
  });

  testWidgets('DropdownButtonFormField - disabled hint should be of same size as enabled hint', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();

747
    Widget build({ List<String>? items}) {
748 749 750 751 752 753 754 755
      return buildFormFrame(
        items: items,
        buttonKey: buttonKey,
        value: null,
        hint: const Text('enabled'),
        disabledHint: const Text('disabled'),
      );
    }
756
    await tester.pumpWidget(build());
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    final RenderBox disabledHintBox = tester.renderObject<RenderBox>(
      find.byKey(buttonKey),
    );

    await tester.pumpWidget(build(items: menuItems));
    final RenderBox enabledHintBox = tester.renderObject<RenderBox>(
      find.byKey(buttonKey),
    );
    expect(enabledHintBox.localToGlobal(Offset.zero), equals(disabledHintBox.localToGlobal(Offset.zero)));
    expect(enabledHintBox.size, equals(disabledHintBox.size));
  });

  testWidgets('DropdownButtonFormField - Custom icon size and colors', (WidgetTester tester) async {
    final Key iconKey = UniqueKey();
    final Icon customIcon = Icon(Icons.assessment, key: iconKey);

    await tester.pumpWidget(buildFormFrame(
      icon: customIcon,
      iconSize: 30.0,
      iconEnabledColor: Colors.pink,
      iconDisabledColor: Colors.orange,
      onChanged: onChanged,
    ));

    // test for size
    final RenderBox icon = tester.renderObject(find.byKey(iconKey));
    expect(icon.size, const Size(30.0, 30.0));

    // test for enabled color
    final RichText enabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
787
    expect(enabledRichText.text.style!.color, Colors.pink);
788 789 790 791 792 793 794 795 796 797 798

    // test for disabled color
    await tester.pumpWidget(buildFormFrame(
      icon: customIcon,
      iconSize: 30.0,
      iconEnabledColor: Colors.pink,
      iconDisabledColor: Colors.orange,
      items: null,
    ));

    final RichText disabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
799
    expect(disabledRichText.text.style!.color, Colors.orange);
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  });

  testWidgets('DropdownButtonFormField - default elevation', (WidgetTester tester) async {
    final Key buttonKey = UniqueKey();
    debugDisableShadows = false;
    await tester.pumpWidget(buildFormFrame(
      buttonKey: buttonKey,
      onChanged: onChanged,
    ));
    await tester.tap(find.byKey(buttonKey));
    await tester.pumpAndSettle();

    final Finder customPaint = find.ancestor(
      of: find.text('one').last,
      matching: find.byType(CustomPaint),
    ).last;

    // Verifying whether or not default elevation(i.e. 8) paints desired shadow
    verifyPaintedShadow(customPaint, 8);
    debugDisableShadows = true;
  });

  testWidgets('DropdownButtonFormField - custom elevation', (WidgetTester tester) async {
    debugDisableShadows = false;
    final Key buttonKeyOne = UniqueKey();
    final Key buttonKeyTwo = UniqueKey();

    await tester.pumpWidget(buildFormFrame(
      buttonKey: buttonKeyOne,
      elevation: 16,
      onChanged: onChanged,
    ));
    await tester.tap(find.byKey(buttonKeyOne));
    await tester.pumpAndSettle();

    final Finder customPaintOne = find.ancestor(
      of: find.text('one').last,
      matching: find.byType(CustomPaint),
    ).last;

    verifyPaintedShadow(customPaintOne, 16);
    await tester.tap(find.text('one').last);
    await tester.pumpWidget(buildFormFrame(
      buttonKey: buttonKeyTwo,
      elevation: 24,
      onChanged: onChanged,
    ));
    await tester.tap(find.byKey(buttonKeyTwo));
    await tester.pumpAndSettle();

    final Finder customPaintTwo = find.ancestor(
      of: find.text('one').last,
      matching: find.byType(CustomPaint),
    ).last;

    verifyPaintedShadow(customPaintTwo, 24);
    debugDisableShadows = true;
  });

  testWidgets('DropdownButtonFormField does not allow duplicate item values', (WidgetTester tester) async {
    final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'c']
      .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList();

868 869
    await expectLater(
      () => tester.pumpWidget(
870 871 872 873
        MaterialApp(
          home: Scaffold(
            body: DropdownButtonFormField<String>(
              value: 'c',
874
              onChanged: (String? newValue) {},
875 876 877 878
              items: itemsWithDuplicateValues,
            ),
          ),
        ),
879
      ),
880
      throwsA(isAssertionError.having(
881 882
        (AssertionError error) => error.toString(),
        '.toString()',
883
        contains("There should be exactly one item with [DropdownButton]'s value"),
884 885
      )),
    );
886 887 888 889 890 891 892 893 894 895 896
  });

  testWidgets('DropdownButtonFormField value should only appear in one menu item', (WidgetTester tester) async {
    final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'd']
      .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList();

897 898
    await expectLater(
      () => tester.pumpWidget(
899 900 901 902
        MaterialApp(
          home: Scaffold(
            body: DropdownButton<String>(
              value: 'e',
903
              onChanged: (String? newValue) {},
904 905 906 907
              items: itemsWithDuplicateValues,
            ),
          ),
        ),
908
      ),
909
      throwsA(isAssertionError.having(
910 911
        (AssertionError error) => error.toString(),
        '.toString()',
912
        contains("There should be exactly one item with [DropdownButton]'s value"),
913 914
      )),
    );
915
  });
916 917 918 919 920 921 922

  testWidgets('DropdownButtonFormField - selectedItemBuilder builds custom buttons', (WidgetTester tester) async {
    const List<String> items = <String>[
      'One',
      'Two',
      'Three',
    ];
923
    String? selectedItem = items[0];
924 925 926 927 928 929 930 931

    await tester.pumpWidget(
      StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return MaterialApp(
            home: Scaffold(
              body: DropdownButtonFormField<String>(
                value: selectedItem,
932
                onChanged: (String? string) => setState(() => selectedItem = string),
933 934 935 936 937 938 939 940 941 942
                selectedItemBuilder: (BuildContext context) {
                  int index = 0;
                  return items.map((String string) {
                    index += 1;
                    return Text('$string as an Arabic numeral: $index');
                  }).toList();
                },
                items: items.map((String string) {
                  return DropdownMenuItem<String>(
                    value: string,
943
                    child: Text(string),
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
                  );
                }).toList(),
              ),
            ),
          );
        },
      ),
    );

    expect(find.text('One as an Arabic numeral: 1'), findsOneWidget);
    await tester.tap(find.text('One as an Arabic numeral: 1'));
    await tester.pumpAndSettle();
    await tester.tap(find.text('Two'));
    await tester.pumpAndSettle();
    expect(find.text('Two as an Arabic numeral: 2'), findsOneWidget);
  });
960 961 962

  testWidgets('DropdownButton onTap callback is called when defined', (WidgetTester tester) async {
    int dropdownButtonTapCounter = 0;
963 964 965 966
    String? value = 'one';
    void onChanged(String? newValue) {
      value = newValue;
    }
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    void onTap() { dropdownButtonTapCounter += 1; }

    Widget build() => buildFormFrame(
      value: value,
      onChanged: onChanged,
      onTap: onTap,
    );
    await tester.pumpWidget(build());

    expect(dropdownButtonTapCounter, 0);

    // Tap dropdown button.
    await tester.tap(find.text('one'));
    await tester.pumpAndSettle();

    expect(value, equals('one'));
    expect(dropdownButtonTapCounter, 1); // Should update counter.

    // Tap dropdown menu item.
    await tester.tap(find.text('three').last);
    await tester.pumpAndSettle();

    expect(value, equals('three'));
    expect(dropdownButtonTapCounter, 1); // Should not change.

    // Tap dropdown button again.
    await tester.tap(find.text('three'));
    await tester.pumpAndSettle();

    expect(value, equals('three'));
    expect(dropdownButtonTapCounter, 2); // Should update counter.

    // Tap dropdown menu item.
    await tester.tap(find.text('two').last);
    await tester.pumpAndSettle();

    expect(value, equals('two'));
    expect(dropdownButtonTapCounter, 2); // Should not change.
  });
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

  testWidgets('DropdownButtonFormField should re-render if value param changes', (WidgetTester tester) async {
    String currentValue = 'two';

    await tester.pumpWidget(
      StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return MaterialApp(
            home: Material(
              child: DropdownButtonFormField<String>(
                value: currentValue,
                onChanged: onChanged,
                items: menuItems.map((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                    onTap: () {
                      setState(() {
                        currentValue = value;
                      });
                    },
                  );
                }).toList(),
              ),
            ),
          );
        },
      ),
    );

    // Make sure the rendered text value matches the initial state value.
    expect(currentValue, equals('two'));
    expect(find.text(currentValue), findsOneWidget);

    // Tap the DropdownButtonFormField widget
    await tester.tap(find.byType(dropdownButtonType));
    await tester.pumpAndSettle();

    // Tap the first dropdown menu item.
    await tester.tap(find.text('one').last);
    await tester.pumpAndSettle();

    // Make sure the rendered text value matches the updated state value.
    expect(currentValue, equals('one'));
    expect(find.text(currentValue), findsOneWidget);
  });
1052 1053

  testWidgets('autovalidateMode is passed to super', (WidgetTester tester) async {
1054
    int validateCalled = 0;
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Center(
            child: DropdownButtonFormField<String>(
              autovalidateMode: AutovalidateMode.always,
              items: menuItems.map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: onChanged,
1069
              validator: (String? value) {
1070
                validateCalled++;
1071 1072 1073 1074 1075 1076 1077 1078
                return null;
              },
            ),
          ),
        ),
      ),
    );

1079
    expect(validateCalled, 1);
1080 1081
  });

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  testWidgets('DropdownButtonFormField - Custom button alignment', (WidgetTester tester) async {
    await tester.pumpWidget(buildFormFrame(
      buttonAlignment: AlignmentDirectional.center,
      items: <String>['one'],
      value: 'one',
    ));

    final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byType(IndexedStack));
    final RenderBox selectedItemBox = tester.renderObject(find.text('one'));

    // Should be center-center aligned.
    expect(
      buttonBox.localToGlobal(Offset(buttonBox.size.width / 2.0, buttonBox.size.height / 2.0)),
      selectedItemBox.localToGlobal(Offset(selectedItemBox.size.width / 2.0, selectedItemBox.size.height / 2.0)),
    );
  });
1098
}