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

5 6
import 'dart:ui';

7
import 'package:flutter/material.dart';
8
import 'package:flutter/rendering.dart';
9 10
import 'package:flutter_test/flutter_test.dart';

11
import '../rendering/mock_canvas.dart';
12
import '../widgets/semantics_tester.dart';
13
import 'feedback_tester.dart';
14

15
class MockOnPressedFunction {
16 17
  int called = 0;

18
  void handler() {
19 20 21 22
    called++;
  }
}

23
void main() {
24
  late MockOnPressedFunction mockOnPressedFunction;
25 26
  const ColorScheme colorScheme = ColorScheme.light();
  final ThemeData theme = ThemeData.from(colorScheme: colorScheme);
27
  setUp(() {
28
    mockOnPressedFunction = MockOnPressedFunction();
29 30
  });

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  testWidgets('test icon is findable by key', (WidgetTester tester) async {
    const ValueKey<String> key = ValueKey<String>('icon-button');
    await tester.pumpWidget(
      wrap(
        useMaterial3: true,
        child: IconButton(
          key: key,
          onPressed: () {},
          icon: const Icon(Icons.link),
        ),
      ),
    );

    expect(find.byKey(key), findsOneWidget);
  });

47
  testWidgets('test default icon buttons are sized up to 48', (WidgetTester tester) async {
48
    final bool material3 = theme.useMaterial3;
49
    await tester.pumpWidget(
Ian Hickson's avatar
Ian Hickson committed
50
      wrap(
51 52 53 54 55
        useMaterial3: material3,
        child: IconButton(
          onPressed: mockOnPressedFunction.handler,
          icon: const Icon(Icons.link),
        ),
56 57 58
      ),
    );

59
    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
60
    expect(iconButton.size, const Size(48.0, 48.0));
61

62 63 64 65 66
    await tester.tap(find.byType(IconButton));
    expect(mockOnPressedFunction.called, 1);
  });

  testWidgets('test small icons are sized up to 48dp', (WidgetTester tester) async {
67
    final bool material3 = theme.useMaterial3;
68
    await tester.pumpWidget(
Ian Hickson's avatar
Ian Hickson committed
69
      wrap(
70 71 72 73 74 75 76
        useMaterial3: material3,
        child: IconButton(
          iconSize: 10.0,
          onPressed: mockOnPressedFunction.handler,
          icon: const Icon(Icons.link),
        ),
      )
77 78
    );

79
    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
80
    expect(iconButton.size, const Size(48.0, 48.0));
81 82 83
  });

  testWidgets('test icons can be small when total size is >48dp', (WidgetTester tester) async {
84
    final bool material3 = theme.useMaterial3;
85
    await tester.pumpWidget(
Ian Hickson's avatar
Ian Hickson committed
86
      wrap(
87 88 89 90 91 92 93 94
        useMaterial3: material3,
        child: IconButton(
          iconSize: 10.0,
          padding: const EdgeInsets.all(30.0),
          onPressed: mockOnPressedFunction.handler,
          icon: const Icon(Icons.link),
        ),
      )
95 96
    );

97
    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
98
    expect(iconButton.size, const Size(70.0, 70.0));
99 100
  });

101
  testWidgets('when both iconSize and IconTheme.of(context).size are null, size falls back to 24.0', (WidgetTester tester) async {
102
    final bool material3 = theme.useMaterial3;
103 104
    await tester.pumpWidget(
      wrap(
105 106 107 108 109 110 111 112 113 114
        useMaterial3: material3,
        child: IconTheme(
          data: const IconThemeData(),
          child: IconButton(
            focusNode: FocusNode(debugLabel: 'Ink Focus'),
            onPressed: mockOnPressedFunction.handler,
            icon: const Icon(Icons.link),
          ),
        )
      )
115 116 117 118 119 120 121 122
    );

    final RenderBox icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(24.0, 24.0));
  });

  testWidgets('when null, iconSize is overridden by closest IconTheme', (WidgetTester tester) async {
    RenderBox icon;
123
    final bool material3 = theme.useMaterial3;
124 125 126

    await tester.pumpWidget(
      wrap(
127
        useMaterial3: material3,
128 129 130 131 132 133 134
        child: IconTheme(
          data: const IconThemeData(size: 10),
          child: IconButton(
            onPressed: mockOnPressedFunction.handler,
            icon: const Icon(Icons.link),
          ),
        )
135
      )
136 137 138 139 140 141 142
    );

    icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(10.0, 10.0));

    await tester.pumpWidget(
      wrap(
143 144 145 146 147 148 149 150 151 152 153 154
        useMaterial3: material3,
        child: Theme(
          data: ThemeData(
            useMaterial3: material3,
            iconTheme: const IconThemeData(size: 10),
          ),
          child: IconButton(
            onPressed: mockOnPressedFunction.handler,
            icon: const Icon(Icons.link),
          ),
        )
      )
155 156 157 158 159 160 161
    );

    icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(10.0, 10.0));

    await tester.pumpWidget(
      wrap(
162 163 164 165 166 167 168 169 170 171 172
        useMaterial3: material3,
        child: Theme(
          data: ThemeData(
            useMaterial3: material3,
            iconTheme: const IconThemeData(size: 20),
          ),
          child: IconTheme(
            data: const IconThemeData(size: 10),
            child: IconButton(
              onPressed: mockOnPressedFunction.handler,
              icon: const Icon(Icons.link),
173
            ),
174 175
          ),
        )
176 177 178 179 180 181 182 183
      ),
    );

    icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(10.0, 10.0));

    await tester.pumpWidget(
      wrap(
184 185 186 187 188 189 190 191 192 193 194
        useMaterial3: material3,
        child: IconTheme(
          data: const IconThemeData(size: 20),
          child: Theme(
            data: ThemeData(
              useMaterial3: material3,
              iconTheme: const IconThemeData(size: 10),
            ),
            child: IconButton(
              onPressed: mockOnPressedFunction.handler,
              icon: const Icon(Icons.link),
195
            ),
196 197
          ),
        )
198 199 200 201 202 203 204 205
      ),
    );

    icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(10.0, 10.0));
  });

  testWidgets('when non-null, iconSize precedes IconTheme.of(context).size', (WidgetTester tester) async {
206
    final bool material3 = theme.useMaterial3;
207 208
    await tester.pumpWidget(
      wrap(
209 210 211 212 213 214 215 216 217
        useMaterial3: material3,
        child: IconTheme(
          data: const IconThemeData(size: 30.0),
          child: IconButton(
            iconSize: 10.0,
            onPressed: mockOnPressedFunction.handler,
            icon: const Icon(Icons.link),
          ),
        )
218 219 220 221 222 223 224
      ),
    );

    final RenderBox icon = tester.renderObject(find.byType(Icon));
    expect(icon.size, const Size(10.0, 10.0));
  });

225 226
  testWidgets('Small icons with non-null constraints can be <48dp for M2, but =48dp for M3', (WidgetTester tester) async {
    final bool material3 = theme.useMaterial3;
227 228
    await tester.pumpWidget(
      wrap(
229
        useMaterial3: material3,
230 231
        child: IconButton(
          iconSize: 10.0,
232
          onPressed: mockOnPressedFunction.handler,
233 234
          icon: const Icon(Icons.link),
          constraints: const BoxConstraints(),
235 236
        )
      )
237 238 239
    );

    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
240
    final RenderBox icon = tester.renderObject(find.byType(Icon));
241 242 243

    // By default IconButton has a padding of 8.0 on all sides, so both
    // width and height are 10.0 + 2 * 8.0 = 26.0
244 245 246 247
    // M3 IconButton is a subclass of ButtonStyleButton which has a minimum
    // Size(48.0, 48.0).
    expect(iconButton.size, material3 ? const Size(48.0, 48.0) : const Size(26.0, 26.0));
    expect(icon.size, const Size(10.0, 10.0));
248 249 250
  });

  testWidgets('Small icons with non-null constraints and custom padding can be <48dp', (WidgetTester tester) async {
251
    final bool material3 = theme.useMaterial3;
252 253
    await tester.pumpWidget(
      wrap(
254
        useMaterial3: material3,
255 256 257
        child: IconButton(
          iconSize: 10.0,
          padding: const EdgeInsets.all(3.0),
258
          onPressed: mockOnPressedFunction.handler,
259 260 261 262 263 264 265
          icon: const Icon(Icons.link),
          constraints: const BoxConstraints(),
        ),
      ),
    );

    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
266
    final RenderBox icon = tester.renderObject(find.byType(Icon));
267 268 269

    // This IconButton has a padding of 3.0 on all sides, so both
    // width and height are 10.0 + 2 * 3.0 = 16.0
270 271 272 273
    // M3 IconButton is a subclass of ButtonStyleButton which has a minimum
    // Size(48.0, 48.0).
    expect(iconButton.size, material3 ? const Size(48.0, 48.0) : const Size(16.0, 16.0));
    expect(icon.size, const Size(10.0, 10.0));
274 275 276
  });

  testWidgets('Small icons comply with VisualDensity requirements', (WidgetTester tester) async {
277
    final bool material3 = theme.useMaterial3;
278 279
    await tester.pumpWidget(
      wrap(
280
        useMaterial3: material3,
281
        child: Theme(
282
          data: ThemeData(visualDensity: const VisualDensity(horizontal: 1, vertical: -1), useMaterial3: material3),
283 284
          child: IconButton(
            iconSize: 10.0,
285
            onPressed: mockOnPressedFunction.handler,
286 287 288 289 290 291 292 293 294 295 296 297 298
            icon: const Icon(Icons.link),
            constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
          ),
        ),
      ),
    );

    final RenderBox iconButton = tester.renderObject(find.byType(IconButton));

    // VisualDensity(horizontal: 1, vertical: -1) increases the icon's
    // width by 4 pixels and decreases its height by 4 pixels, giving
    // final width 32.0 + 4.0 = 36.0 and
    // final height 32.0 - 4.0 = 28.0
299
    expect(iconButton.size, material3 ? const Size(52.0, 44.0) : const Size(36.0, 28.0));
300 301
  });

302
  testWidgets('test default icon buttons are constrained', (WidgetTester tester) async {
303
    await tester.pumpWidget(
Ian Hickson's avatar
Ian Hickson committed
304
      wrap(
305 306 307 308 309 310 311
        useMaterial3: theme.useMaterial3,
        child: IconButton(
          padding: EdgeInsets.zero,
          onPressed: mockOnPressedFunction.handler,
          icon: const Icon(Icons.ac_unit),
          iconSize: 80.0,
        ),
312 313 314
      ),
    );

315
    final RenderBox box = tester.renderObject(find.byType(IconButton));
316
    expect(box.size, const Size(80.0, 80.0));
317 318
  });

319
  testWidgets('test default icon buttons can be stretched if specified', (WidgetTester tester) async {
320
    await tester.pumpWidget(
321
      Directionality(
322
        textDirection: TextDirection.ltr,
323 324
        child: Material(
          child: Row(
325 326
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
327
              IconButton(
328
                onPressed: mockOnPressedFunction.handler,
329 330 331 332
                icon: const Icon(Icons.ac_unit),
              ),
            ],
          ),
333 334 335 336
        ),
      ),
    );

337
    final RenderBox box = tester.renderObject(find.byType(IconButton));
338
    expect(box.size, const Size(48.0, 600.0));
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

    // Test for Material 3
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: true),
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              IconButton(
                onPressed: mockOnPressedFunction.handler,
                icon: const Icon(Icons.ac_unit),
              ),
            ],
          ),
        ),
      )
    );

    final RenderBox boxM3 = tester.renderObject(find.byType(IconButton));
    expect(boxM3.size, const Size(48.0, 600.0));
361 362 363 364
  });

  testWidgets('test default padding', (WidgetTester tester) async {
    await tester.pumpWidget(
Ian Hickson's avatar
Ian Hickson committed
365
      wrap(
366 367 368 369 370 371
        useMaterial3: theme.useMaterial3,
        child: IconButton(
          onPressed: mockOnPressedFunction.handler,
          icon: const Icon(Icons.ac_unit),
          iconSize: 80.0,
        ),
372
      ),
373 374
    );

375
    final RenderBox box = tester.renderObject(find.byType(IconButton));
376
    expect(box.size, const Size(96.0, 96.0));
377 378 379 380
  });

  testWidgets('test tooltip', (WidgetTester tester) async {
    await tester.pumpWidget(
381
      MaterialApp(
382
        theme: theme,
383 384 385
        home: Material(
          child: Center(
            child: IconButton(
386
              onPressed: mockOnPressedFunction.handler,
387
              icon: const Icon(Icons.ac_unit),
388 389 390 391 392 393 394 395 396
            ),
          ),
        ),
      ),
    );

    expect(find.byType(Tooltip), findsNothing);

    // Clear the widget tree.
397
    await tester.pumpWidget(Container(key: UniqueKey()));
398 399

    await tester.pumpWidget(
400
      MaterialApp(
401
        theme: theme,
402 403 404
        home: Material(
          child: Center(
            child: IconButton(
405
              onPressed: mockOnPressedFunction.handler,
406
              icon: const Icon(Icons.ac_unit),
407 408 409 410 411 412 413 414 415 416 417 418
              tooltip: 'Test tooltip',
            ),
          ),
        ),
      ),
    );

    expect(find.byType(Tooltip), findsOneWidget);
    expect(find.byTooltip('Test tooltip'), findsOneWidget);

    await tester.tap(find.byTooltip('Test tooltip'));
    expect(mockOnPressedFunction.called, 1);
419 420 421 422
  });

  testWidgets('IconButton AppBar size', (WidgetTester tester) async {
    await tester.pumpWidget(
423
      MaterialApp(
424
        theme: theme,
425 426
        home: Scaffold(
          appBar: AppBar(
427
            actions: <Widget>[
428
              IconButton(
429
                padding: EdgeInsets.zero,
430
                onPressed: mockOnPressedFunction.handler,
431 432 433 434
                icon: const Icon(Icons.ac_unit),
              ),
            ],
          ),
435 436
        ),
      ),
437 438
    );

439 440
    final RenderBox barBox = tester.renderObject(find.byType(AppBar));
    final RenderBox iconBox = tester.renderObject(find.byType(IconButton));
441 442
    expect(iconBox.size.height, equals(barBox.size.height));
  });
443 444 445

  // This test is very similar to the '...explicit splashColor and highlightColor' test
  // in buttons_test.dart. If you change this one, you may want to also change that one.
446
  testWidgets('IconButton with explicit splashColor and highlightColor - M2', (WidgetTester tester) async {
447 448
    const Color directSplashColor = Color(0xFF00000F);
    const Color directHighlightColor = Color(0xFF0000F0);
449

Ian Hickson's avatar
Ian Hickson committed
450
    Widget buttonWidget = wrap(
451 452 453 454 455 456 457
      useMaterial3: false,
      child: IconButton(
        icon: const Icon(Icons.android),
        splashColor: directSplashColor,
        highlightColor: directHighlightColor,
        onPressed: () { /* enable the button */ },
      ),
458 459 460
    );

    await tester.pumpWidget(
461
      Theme(
462
        data: ThemeData(useMaterial3: false),
463 464 465 466 467 468 469 470 471 472 473 474 475
        child: buttonWidget,
      ),
    );

    final Offset center = tester.getCenter(find.byType(IconButton));
    final TestGesture gesture = await tester.startGesture(center);
    await tester.pump(); // start gesture
    await tester.pump(const Duration(milliseconds: 200)); // wait for splash to be well under way

    expect(
      Material.of(tester.element(find.byType(IconButton))),
      paints
        ..circle(color: directSplashColor)
476
        ..circle(color: directHighlightColor),
477 478
    );

479 480
    const Color themeSplashColor1 = Color(0xFF000F00);
    const Color themeHighlightColor1 = Color(0xFF00FF00);
481

Ian Hickson's avatar
Ian Hickson committed
482
    buttonWidget = wrap(
483 484 485 486 487
      useMaterial3: false,
      child: IconButton(
        icon: const Icon(Icons.android),
        onPressed: () { /* enable the button */ },
      ),
488 489 490
    );

    await tester.pumpWidget(
491 492
      Theme(
        data: ThemeData(
493 494
          highlightColor: themeHighlightColor1,
          splashColor: themeSplashColor1,
495
          useMaterial3: false,
496 497 498 499 500 501 502 503 504
        ),
        child: buttonWidget,
      ),
    );

    expect(
      Material.of(tester.element(find.byType(IconButton))),
      paints
        ..circle(color: themeSplashColor1)
505
        ..circle(color: themeHighlightColor1),
506 507
    );

508 509
    const Color themeSplashColor2 = Color(0xFF002200);
    const Color themeHighlightColor2 = Color(0xFF001100);
510 511

    await tester.pumpWidget(
512 513
      Theme(
        data: ThemeData(
514 515
          highlightColor: themeHighlightColor2,
          splashColor: themeSplashColor2,
516
          useMaterial3: false,
517 518 519 520 521 522 523 524 525
        ),
        child: buttonWidget, // same widget, so does not get updated because of us
      ),
    );

    expect(
      Material.of(tester.element(find.byType(IconButton))),
      paints
        ..circle(color: themeSplashColor2)
526
        ..circle(color: themeHighlightColor2),
527 528 529 530
    );

    await gesture.up();
  });
531

532
  testWidgets('IconButton with explicit splash radius - M2', (WidgetTester tester) async {
533 534 535
    const double splashRadius = 30.0;
    await tester.pumpWidget(
      MaterialApp(
536
        theme: ThemeData(useMaterial3: false),
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
        home: Material(
          child: Center(
            child: IconButton(
              icon: const Icon(Icons.android),
              splashRadius: splashRadius,
              onPressed: () { /* enable the button */ },
            ),
          ),
        ),
      ),
    );

    final Offset center = tester.getCenter(find.byType(IconButton));
    final TestGesture gesture = await tester.startGesture(center);
    await tester.pump(); // Start gesture.
    await tester.pump(const Duration(milliseconds: 1000)); // Wait for splash to be well under way.

    expect(
      Material.of(tester.element(find.byType(IconButton))),
      paints
557
        ..circle(radius: splashRadius),
558 559 560 561 562
    );

    await gesture.up();
  });

563
  testWidgets('IconButton Semantics (enabled) - M2', (WidgetTester tester) async {
564
    final SemanticsTester semantics = SemanticsTester(tester);
565 566 567

    await tester.pumpWidget(
      wrap(
568
        useMaterial3: false,
569
        child: IconButton(
570
          onPressed: mockOnPressedFunction.handler,
571 572 573 574 575
          icon: const Icon(Icons.link, semanticLabel: 'link'),
        ),
      ),
    );

576
    expect(semantics, hasSemantics(TestSemantics.root(
577
      children: <TestSemantics>[
578
        TestSemantics.rootChild(
Dan Field's avatar
Dan Field committed
579
          rect: const Rect.fromLTRB(0.0, 0.0, 48.0, 48.0),
580
          actions: <SemanticsAction>[
581
            SemanticsAction.tap,
582 583 584
          ],
          flags: <SemanticsFlag>[
            SemanticsFlag.hasEnabledState,
585
            SemanticsFlag.isButton,
586 587
            SemanticsFlag.isEnabled,
            SemanticsFlag.isFocusable,
588
          ],
589
          label: 'link',
590
        ),
591
      ],
592 593 594 595
    ), ignoreId: true, ignoreTransform: true));

    semantics.dispose();
  });
596

597
  testWidgets('IconButton Semantics (disabled) - M2', (WidgetTester tester) async {
598
    final SemanticsTester semantics = SemanticsTester(tester);
599 600 601

    await tester.pumpWidget(
      wrap(
602
        useMaterial3: false,
603 604
        child: const IconButton(
          onPressed: null,
605
          icon: Icon(Icons.link, semanticLabel: 'link'),
606 607 608 609
        ),
      ),
    );

610
    expect(semantics, hasSemantics(TestSemantics.root(
611
        children: <TestSemantics>[
612
          TestSemantics.rootChild(
Dan Field's avatar
Dan Field committed
613
            rect: const Rect.fromLTRB(0.0, 0.0, 48.0, 48.0),
614 615
            flags: <SemanticsFlag>[
              SemanticsFlag.hasEnabledState,
616
              SemanticsFlag.isButton,
617 618
            ],
            label: 'link',
619
          ),
620
        ],
621 622 623 624
    ), ignoreId: true, ignoreTransform: true));

    semantics.dispose();
  });
625 626 627 628 629

  testWidgets('IconButton loses focus when disabled.', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode(debugLabel: 'IconButton');
    await tester.pumpWidget(
      wrap(
630
        useMaterial3: theme.useMaterial3,
631 632 633 634 635 636 637 638 639 640 641 642 643 644
        child: IconButton(
          focusNode: focusNode,
          autofocus: true,
          onPressed: () {},
          icon: const Icon(Icons.link),
        ),
      ),
    );

    await tester.pump();
    expect(focusNode.hasPrimaryFocus, isTrue);

    await tester.pumpWidget(
      wrap(
645
        useMaterial3: theme.useMaterial3,
646 647 648 649 650 651 652 653 654 655 656 657
        child: IconButton(
          focusNode: focusNode,
          autofocus: true,
          onPressed: null,
          icon: const Icon(Icons.link),
        ),
      ),
    );
    await tester.pump();
    expect(focusNode.hasPrimaryFocus, isFalse);
  });

658 659 660 661
  testWidgets('IconButton keeps focus when disabled in directional navigation mode.', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode(debugLabel: 'IconButton');
    await tester.pumpWidget(
      wrap(
662
        useMaterial3: theme.useMaterial3,
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        child: MediaQuery(
          data: const MediaQueryData(
            navigationMode: NavigationMode.directional,
          ),
          child: IconButton(
            focusNode: focusNode,
            autofocus: true,
            onPressed: () {},
            icon: const Icon(Icons.link),
          ),
        ),
      ),
    );

    await tester.pump();
    expect(focusNode.hasPrimaryFocus, isTrue);

    await tester.pumpWidget(
      wrap(
682
        useMaterial3: theme.useMaterial3,
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        child: MediaQuery(
          data: const MediaQueryData(
            navigationMode: NavigationMode.directional,
          ),
          child: IconButton(
            focusNode: focusNode,
            autofocus: true,
            onPressed: null,
            icon: const Icon(Icons.link),
          ),
        ),
      ),
    );
    await tester.pump();
    expect(focusNode.hasPrimaryFocus, isTrue);
  });

700 701 702 703 704 705
  testWidgets("Disabled IconButton can't be traversed to when disabled.", (WidgetTester tester) async {
    final FocusNode focusNode1 = FocusNode(debugLabel: 'IconButton 1');
    final FocusNode focusNode2 = FocusNode(debugLabel: 'IconButton 2');

    await tester.pumpWidget(
      wrap(
706
        useMaterial3: theme.useMaterial3,
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
        child: Column(
          children: <Widget>[
            IconButton(
              focusNode: focusNode1,
              autofocus: true,
              onPressed: () {},
              icon: const Icon(Icons.link),
            ),
            IconButton(
              focusNode: focusNode2,
              onPressed: null,
              icon: const Icon(Icons.link),
            ),
          ],
        ),
      ),
    );
    await tester.pump();

    expect(focusNode1.hasPrimaryFocus, isTrue);
    expect(focusNode2.hasPrimaryFocus, isFalse);

    expect(focusNode1.nextFocus(), isTrue);
    await tester.pump();

    expect(focusNode1.hasPrimaryFocus, isTrue);
    expect(focusNode2.hasPrimaryFocus, isFalse);
  });
735 736

  group('feedback', () {
737
    late FeedbackTester feedback;
738 739 740 741 742 743

    setUp(() {
      feedback = FeedbackTester();
    });

    tearDown(() {
744
      feedback.dispose();
745 746 747
    });

    testWidgets('IconButton with disabled feedback', (WidgetTester tester) async {
748 749 750 751 752 753 754
      final Widget button = Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: IconButton(
            onPressed: () {},
            enableFeedback: false,
            icon: const Icon(Icons.link),
755 756
          ),
        ),
757 758 759 760 761 762 763
      );

      await tester.pumpWidget(
        theme.useMaterial3
          ? MaterialApp(theme: theme, home: button)
          : Material(child: button)
      );
764 765 766 767 768 769 770
      await tester.tap(find.byType(IconButton), pointer: 1);
      await tester.pump(const Duration(seconds: 1));
      expect(feedback.clickSoundCount, 0);
      expect(feedback.hapticCount, 0);
    });

    testWidgets('IconButton with enabled feedback', (WidgetTester tester) async {
771 772 773 774 775 776
      final Widget button = Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: IconButton(
            onPressed: () {},
            icon: const Icon(Icons.link),
777 778
          ),
        ),
779 780 781 782 783 784 785
      );

      await tester.pumpWidget(
        theme.useMaterial3
          ? MaterialApp(theme: theme, home: button)
          : Material(child: button),
      );
786 787 788 789 790 791 792
      await tester.tap(find.byType(IconButton), pointer: 1);
      await tester.pump(const Duration(seconds: 1));
      expect(feedback.clickSoundCount, 1);
      expect(feedback.hapticCount, 0);
    });

    testWidgets('IconButton with enabled feedback by default', (WidgetTester tester) async {
793 794 795 796 797 798
      final Widget button = Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: IconButton(
            onPressed: () {},
            icon: const Icon(Icons.link),
799 800
          ),
        ),
801 802 803 804 805 806 807
      );

      await tester.pumpWidget(
        theme.useMaterial3
          ? MaterialApp(theme: theme, home: button)
          : Material(child: button),
      );
808 809 810 811 812 813
      await tester.tap(find.byType(IconButton), pointer: 1);
      await tester.pump(const Duration(seconds: 1));
      expect(feedback.clickSoundCount, 1);
      expect(feedback.hapticCount, 0);
    });
  });
814 815 816

  testWidgets('IconButton responds to density changes.', (WidgetTester tester) async {
    const Key key = Key('test');
817
    final bool material3 = theme.useMaterial3;
818
    Future<void> buildTest(VisualDensity visualDensity) async {
819
      return tester.pumpWidget(
820
        MaterialApp(
821
          theme: theme,
822 823 824 825 826 827 828 829 830 831 832 833 834 835
          home: Material(
            child: Center(
              child: IconButton(
                visualDensity: visualDensity,
                key: key,
                onPressed: () {},
                icon: const Icon(Icons.play_arrow),
              ),
            ),
          ),
        ),
      );
    }

836
    await buildTest(VisualDensity.standard);
837
    final RenderBox box = tester.renderObject(find.byType(IconButton));
838 839 840 841 842
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(48, 48)));

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
    await tester.pumpAndSettle();
843
    expect(box.size, equals(material3 ? const Size(64, 64) : const Size(60, 60)));
844 845 846

    await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
    await tester.pumpAndSettle();
847 848 849 850 851 852
    // IconButton is a subclass of ButtonStyleButton in Material 3, so the negative
    // visualDensity cannot be applied to horizontal padding.
    // The size of the Button with padding is (24 + 8 + 8, 24) -> (40, 24)
    // minSize of M3 IconButton is (48 - 12, 48 - 12) -> (36, 36)
    // So, the button size in Material 3 is (40, 36)
    expect(box.size, equals(material3 ? const Size(40, 36) : const Size(40, 40)));
853 854 855

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0));
    await tester.pumpAndSettle();
856
    expect(box.size, equals(material3 ? const Size(64, 36) : const Size(60, 40)));
857
  });
858 859 860 861

  testWidgets('IconButton.mouseCursor changes cursor on hover', (WidgetTester tester) async {
    // Test argument works
    await tester.pumpWidget(
862 863 864 865 866 867 868 869 870 871 872
      MaterialApp(
        theme: theme,
        home: Material(
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: IconButton(
                onPressed: () {},
                mouseCursor: SystemMouseCursors.forbidden,
                icon: const Icon(Icons.play_arrow),
              ),
873 874 875 876 877 878 879 880 881 882 883
            ),
          ),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));

    await tester.pump();

884
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
885 886 887

    // Test default is click
    await tester.pumpWidget(
888 889 890 891 892 893 894 895 896 897
      MaterialApp(
        theme: theme,
        home: Material(
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: IconButton(
                onPressed: () {},
                icon: const Icon(Icons.play_arrow),
              ),
898 899 900 901 902 903
            ),
          ),
        ),
      ),
    );

904
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
905
  });
906

907
  testWidgets('disabled IconButton has basic mouse cursor', (WidgetTester tester) async {
908
    await tester.pumpWidget(
909 910 911 912 913 914 915 916 917 918
      MaterialApp(
        theme: theme,
        home: const Material(
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: IconButton(
                onPressed: null, // null value indicates IconButton is disabled
                icon: Icon(Icons.play_arrow),
              ),
919 920 921 922 923 924 925 926 927 928 929
            ),
          ),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));

    await tester.pump();

930
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
931 932 933 934
  });

  testWidgets('IconButton.mouseCursor overrides implicit setting of mouse cursor', (WidgetTester tester) async {
    await tester.pumpWidget(
935 936 937 938 939 940 941 942 943 944 945
      MaterialApp(
        theme: theme,
        home: const Material(
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: IconButton(
                onPressed: null,
                mouseCursor: SystemMouseCursors.none,
                icon: Icon(Icons.play_arrow),
              ),
946 947 948 949 950 951 952 953 954 955 956
            ),
          ),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));

    await tester.pump();

957
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
958 959

    await tester.pumpWidget(
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 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
      MaterialApp(
        theme: theme,
        home: Material(
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: IconButton(
                onPressed: () {},
                mouseCursor: SystemMouseCursors.none,
                icon: const Icon(Icons.play_arrow),
              ),
            ),
          ),
        ),
      ),
    );

    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
  });


  testWidgets('IconButton defaults - M3', (WidgetTester tester) async {
    final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);

    // Enabled IconButton
    await tester.pumpWidget(
      MaterialApp(
        theme: themeM3,
        home: Center(
          child: IconButton(
            onPressed: () { },
            icon: const Icon(Icons.ac_unit),
          ),
        ),
      ),
    );

    final Finder buttonMaterial = find.descendant(
      of: find.byType(IconButton),
      matching: find.byType(Material),
    );

    Material material = tester.widget<Material>(buttonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, Colors.transparent);
    expect(material.elevation, 0.0);
    expect(material.shadowColor, null);
    expect(material.shape, const StadiumBorder());
    expect(material.textStyle, null);
    expect(material.type, MaterialType.button);

    final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
    expect(align.alignment, Alignment.center);

    final Offset center = tester.getCenter(find.byType(IconButton));
    final TestGesture gesture = await tester.startGesture(center);
    await tester.pump(); // start the splash animation
    await tester.pump(const Duration(milliseconds: 100)); // splash is underway

    await gesture.up();
    await tester.pumpAndSettle();
    material = tester.widget<Material>(buttonMaterial);
    // No change vs enabled and not pressed.
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, Colors.transparent);
    expect(material.elevation, 0.0);
    expect(material.shadowColor, null);
    expect(material.shape, const StadiumBorder());
    expect(material.textStyle, null);
    expect(material.type, MaterialType.button);

1037
    // Disabled IconButton
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    await tester.pumpWidget(
      MaterialApp(
        theme: themeM3,
        home: const Center(
          child: IconButton(
            onPressed: null,
            icon: Icon(Icons.ac_unit),
          ),
        ),
      ),
    );

    material = tester.widget<Material>(buttonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, Colors.transparent);
    expect(material.elevation, 0.0);
    expect(material.shadowColor, null);
    expect(material.shape, const StadiumBorder());
    expect(material.textStyle, null);
    expect(material.type, MaterialType.button);
  });

  testWidgets('Default IconButton meets a11y contrast guidelines - M3', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: Scaffold(
          body: Center(
            child: IconButton(
              onPressed: () { },
              focusNode: focusNode,
              icon: const Icon(Icons.ac_unit),
            ),
          ),
        ),
      ),
    );

    // Default, not disabled.
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    // Hovered.
    final Offset center = tester.getCenter(find.byType(IconButton));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    // Highlighted (pressed).
    await gesture.down(center);
    await tester.pump(); // Start the splash and highlight animations.
    await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    await gesture.removePointer();
  },
    skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
  );

  testWidgets('IconButton uses stateful color for icon color in different states - M3', (WidgetTester tester) async {
1111
    bool isSelected = false;
1112 1113 1114 1115 1116 1117
    final FocusNode focusNode = FocusNode();

    const Color pressedColor = Color(0x00000001);
    const Color hoverColor = Color(0x00000002);
    const Color focusedColor = Color(0x00000003);
    const Color defaultColor = Color(0x00000004);
1118
    const Color selectedColor = Color(0x00000005);
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    Color getIconColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return pressedColor;
      }
      if (states.contains(MaterialState.hovered)) {
        return hoverColor;
      }
      if (states.contains(MaterialState.focused)) {
        return focusedColor;
      }
1130 1131 1132
      if (states.contains(MaterialState.selected)) {
        return selectedColor;
      }
1133 1134 1135 1136 1137 1138
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return Scaffold(
              body: Center(
                child: IconButton(
                  style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.resolveWith<Color>(getIconColor),
                  ),
                  isSelected: isSelected,
                  onPressed: () {
                    setState(() {
                      isSelected = !isSelected;
                    });
                  },
                  focusNode: focusNode,
                  icon: const Icon(Icons.ac_unit),
                ),
1156
              ),
1157 1158
            );
          }
1159 1160 1161 1162 1163 1164 1165 1166 1167
        ),
      ),
    );

    Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;

    // Default, not disabled.
    expect(iconColor(), equals(defaultColor));

1168 1169 1170 1171 1172 1173
    // Selected
    final Finder button = find.byType(IconButton);
    await tester.tap(button);
    await tester.pumpAndSettle();
    expect(iconColor(), selectedColor);

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    expect(iconColor(), focusedColor);

    // Hovered.
    final Offset center = tester.getCenter(find.byType(IconButton));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    expect(iconColor(), hoverColor);

    // Highlighted (pressed).
    await gesture.down(center);
    await tester.pump(); // Start the splash and highlight animations.
    await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
    expect(iconColor(), pressedColor);
  });

  testWidgets('Does IconButton contribute semantics - M3', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: Theme(
            data: ThemeData(useMaterial3: true),
            child: IconButton(
              style: const ButtonStyle(
                // Specifying minimumSize to mimic the original minimumSize for
                // RaisedButton so that the semantics tree's rect and transform
                // match the original version of this test.
                minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)),
              ),
              onPressed: () { },
              icon: const Icon(Icons.ac_unit),
            ),
          ),
        ),
      ),
    );

    expect(semantics, hasSemantics(
      TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
            actions: <SemanticsAction>[
              SemanticsAction.tap,
            ],
            rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
            transform: Matrix4.translationValues(356.0, 276.0, 0.0),
            flags: <SemanticsFlag>[
              SemanticsFlag.hasEnabledState,
              SemanticsFlag.isButton,
              SemanticsFlag.isEnabled,
              SemanticsFlag.isFocusable,
            ],
          ),
        ],
      ),
      ignoreId: true,
    ));

    semantics.dispose();
  });

  testWidgets('IconButton size is configurable by ThemeData.materialTapTargetSize - M3', (WidgetTester tester) async {
    Widget buildFrame(MaterialTapTargetSize tapTargetSize) {
      return Theme(
        data: ThemeData(materialTapTargetSize: tapTargetSize, useMaterial3: true),
1247 1248 1249 1250
        child: Directionality(
          textDirection: TextDirection.ltr,
          child: Center(
            child: IconButton(
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
              style: IconButton.styleFrom(minimumSize: const Size(40, 40)),
              icon: const Icon(Icons.ac_unit),
              onPressed: () { },
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded));
    expect(tester.getSize(find.byType(IconButton)), const Size(48.0, 48.0));

    await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap));
    expect(tester.getSize(find.byType(IconButton)), const Size(40.0, 40.0));
  });

  testWidgets('Override IconButton default padding - M3', (WidgetTester tester) async {
    // Use [IconButton]'s padding property to override default value.
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: Scaffold(
          body: Center(
            child: IconButton(
              padding: const EdgeInsets.all(20),
1276
              onPressed: () {},
1277
              icon: const Icon(Icons.ac_unit),
1278 1279 1280
            ),
          ),
        ),
1281 1282 1283 1284 1285 1286 1287
      )
    );

    final Padding paddingWidget1 = tester.widget<Padding>(
      find.descendant(
        of: find.byType(IconButton),
        matching: find.byType(Padding),
1288 1289
      ),
    );
1290
    expect(paddingWidget1.padding, const EdgeInsets.all(20));
1291

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    // Use [IconButton.style]'s padding property to override default value.
    await tester.pumpWidget(
        MaterialApp(
          theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
          home: Scaffold(
            body: Center(
              child: IconButton(
                style: IconButton.styleFrom(padding: const EdgeInsets.all(20)),
                onPressed: () {},
                icon: const Icon(Icons.ac_unit),
              ),
            ),
          ),
        )
    );

    final Padding paddingWidget2 = tester.widget<Padding>(
      find.descendant(
        of: find.byType(IconButton),
        matching: find.byType(Padding),
      ),
    );
    expect(paddingWidget2.padding, const EdgeInsets.all(20));

    // [IconButton.style]'s padding will override [IconButton]'s padding if both
    // values are not null.
    await tester.pumpWidget(
        MaterialApp(
          theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
          home: Scaffold(
            body: Center(
              child: IconButton(
                padding: const EdgeInsets.all(15),
                style: IconButton.styleFrom(padding: const EdgeInsets.all(22)),
                onPressed: () {},
                icon: const Icon(Icons.ac_unit),
              ),
            ),
          ),
        )
    );

    final Padding paddingWidget3 = tester.widget<Padding>(
      find.descendant(
        of: find.byType(IconButton),
        matching: find.byType(Padding),
      ),
    );
    expect(paddingWidget3.padding, const EdgeInsets.all(22));
1341
  });
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

  testWidgets('Default IconButton is not selectable - M3', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: IconButton(icon: const Icon(Icons.ac_unit), onPressed: (){},)
      )
    );

    final Finder button = find.byType(IconButton);
    IconButton buttonWidget() => tester.widget<IconButton>(button);

    Material buttonMaterial() {
      return tester.widget<Material>(
        find.descendant(
          of: find.byType(IconButton),
          matching: find.byType(Material),
        )
      );
    }

    Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;

    expect(buttonWidget().isSelected, null);
    expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
    expect(buttonMaterial().color, Colors.transparent);

    await tester.tap(button); // The non-toggle IconButton should not change appearance after clicking
    await tester.pumpAndSettle();

    expect(buttonWidget().isSelected, null);
    expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
    expect(buttonMaterial().color, Colors.transparent);
  });

  testWidgets('Icon button is selectable when isSelected is not null - M3', (WidgetTester tester) async {
    bool isSelected = false;
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return IconButton(
              isSelected: isSelected,
              icon: const Icon(Icons.ac_unit),
              onPressed: (){
                setState(() {
                  isSelected = !isSelected;
                });
              },
            );
          }
        )
      )
    );

    final Finder button = find.byType(IconButton);
    IconButton buttonWidget() => tester.widget<IconButton>(button);
    Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;

    Material buttonMaterial() {
      return tester.widget<Material>(
        find.descendant(
          of: find.byType(IconButton),
          matching: find.byType(Material),
        )
      );
    }

    expect(buttonWidget().isSelected, false);
    expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
    expect(buttonMaterial().color, Colors.transparent);

    await tester.tap(button); // The toggle IconButton should change appearance after clicking
    await tester.pumpAndSettle();

    expect(buttonWidget().isSelected, true);
    expect(iconColor(), equals(const ColorScheme.light().primary));
    expect(buttonMaterial().color, Colors.transparent);

    await tester.tap(button); // The IconButton should be unselected if it's clicked again
    await tester.pumpAndSettle();

    expect(buttonWidget().isSelected, false);
    expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
    expect(buttonMaterial().color, Colors.transparent);
  });

  testWidgets('The IconButton is in selected status if isSelected is true by default - M3', (WidgetTester tester) async {
    bool isSelected = true;
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return IconButton(
              isSelected: isSelected,
              icon: const Icon(Icons.ac_unit),
              onPressed: (){
                setState(() {
                  isSelected = !isSelected;
                });
              },
            );
          }
        )
      )
    );

    final Finder button = find.byType(IconButton);
    IconButton buttonWidget() => tester.widget<IconButton>(button);
    Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;

    Material buttonMaterial() {
      return tester.widget<Material>(
        find.descendant(
          of: find.byType(IconButton),
          matching: find.byType(Material),
        )
      );
    }

    expect(buttonWidget().isSelected, true);
    expect(iconColor(), equals(const ColorScheme.light().primary));
    expect(buttonMaterial().color, Colors.transparent);

    await tester.tap(button); // The IconButton becomes unselected if it's clicked
    await tester.pumpAndSettle();

    expect(buttonWidget().isSelected, false);
    expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
    expect(buttonMaterial().color, Colors.transparent);
  });

  testWidgets("The selectedIcon is used if it's not null and the button is clicked" , (WidgetTester tester) async {
    bool isSelected = false;
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return IconButton(
              isSelected: isSelected,
              selectedIcon: const Icon(Icons.account_box),
              icon: const Icon(Icons.account_box_outlined),
              onPressed: (){
                setState(() {
                  isSelected = !isSelected;
                });
              },
            );
          }
        )
      )
    );

    final Finder button = find.byType(IconButton);

    expect(find.byIcon(Icons.account_box_outlined), findsOneWidget);
    expect(find.byIcon(Icons.account_box), findsNothing);

    await tester.tap(button); // The icon becomes to selectedIcon
    await tester.pumpAndSettle();

    expect(find.byIcon(Icons.account_box), findsOneWidget);
    expect(find.byIcon(Icons.account_box_outlined), findsNothing);

    await tester.tap(button); // The icon becomes the original icon when it's clicked again
    await tester.pumpAndSettle();

    expect(find.byIcon(Icons.account_box_outlined), findsOneWidget);
    expect(find.byIcon(Icons.account_box), findsNothing);
  });

  testWidgets('The original icon is used for selected and unselected status when selectedIcon is null' , (WidgetTester tester) async {
    bool isSelected = false;
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return IconButton(
              isSelected: isSelected,
              icon: const Icon(Icons.account_box),
              onPressed: (){
                setState(() {
                  isSelected = !isSelected;
                });
              },
            );
          }
        )
      )
    );

    final Finder button = find.byType(IconButton);
    IconButton buttonWidget() => tester.widget<IconButton>(button);

    expect(buttonWidget().isSelected, false);
    expect(buttonWidget().selectedIcon, null);
    expect(find.byIcon(Icons.account_box), findsOneWidget);

    await tester.tap(button); // The icon becomes the original icon when it's clicked again
    await tester.pumpAndSettle();

    expect(buttonWidget().isSelected, true);
    expect(buttonWidget().selectedIcon, null);
    expect(find.byIcon(Icons.account_box), findsOneWidget);
  });

  testWidgets('The selectedIcon is used for disabled button if isSelected is true - M3' , (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: const IconButton(
          isSelected: true,
          icon: Icon(Icons.account_box),
          selectedIcon: Icon(Icons.ac_unit),
          onPressed: null,
        )
      )
    );

    final Finder button = find.byType(IconButton);
    IconButton buttonWidget() => tester.widget<IconButton>(button);

    expect(buttonWidget().isSelected, true);
    expect(find.byIcon(Icons.account_box), findsNothing);
    expect(find.byIcon(Icons.ac_unit), findsOneWidget);
  });
1572
}
Ian Hickson's avatar
Ian Hickson committed
1573

1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
Widget wrap({required Widget child, required bool useMaterial3}) {
  return useMaterial3
      ? MaterialApp(
        theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
        home: FocusTraversalGroup(
            policy: ReadingOrderTraversalPolicy(),
            child: Directionality(
              textDirection: TextDirection.ltr,
              child: Center(child: child),
            )),
      )
      : FocusTraversalGroup(
          policy: ReadingOrderTraversalPolicy(),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Material(
              child: Center(child: child),
            ),
          ),
      );
}

TextStyle? _iconStyle(WidgetTester tester, IconData icon) {
  final RichText iconRichText = tester.widget<RichText>(
    find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
Ian Hickson's avatar
Ian Hickson committed
1599
  );
1600
  return iconRichText.text.style;
Ian Hickson's avatar
Ian Hickson committed
1601
}