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

5
import 'package:flutter/gestures.dart';
6 7
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
8
import 'package:flutter_test/flutter_test.dart';
9
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
10
import '../widgets/semantics_tester.dart';
11 12

void main() {
13 14 15 16
  setUp(() {
    debugResetSemanticsIdCounter();
  });

17
  testWidgetsWithLeakTracking('MaterialButton defaults', (WidgetTester tester) async {
18 19 20 21 22 23 24
    final Finder rawButtonMaterial = find.descendant(
      of: find.byType(MaterialButton),
      matching: find.byType(Material),
    );

    // Enabled MaterialButton
    await tester.pumpWidget(
25 26 27 28 29 30 31 32
      Theme(
        data: ThemeData(useMaterial3: false),
        child: Directionality(
          textDirection: TextDirection.ltr,
          child: MaterialButton(
            onPressed: () { },
            child: const Text('button'),
          ),
33 34 35 36 37 38 39 40 41 42
        ),
      ),
    );
    Material material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, null);
    expect(material.elevation, 2.0);
43
    expect(material.shadowColor, null);
44
    expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))));
45 46 47 48
    expect(material.textStyle!.color, const Color(0xdd000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
49 50 51
    expect(material.type, MaterialType.transparency);

    final Offset center = tester.getCenter(find.byType(MaterialButton));
52
    final TestGesture gesture = await tester.startGesture(center);
53 54 55 56 57 58 59 60 61 62
    await tester.pumpAndSettle();

    // Only elevation changes when enabled and pressed.
    material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, null);
    expect(material.elevation, 8.0);
63
    expect(material.shadowColor, null);
64
    expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))));
65 66 67 68
    expect(material.textStyle!.color, const Color(0xdd000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
69 70 71 72
    expect(material.type, MaterialType.transparency);

    // Disabled MaterialButton
    await tester.pumpWidget(
73 74 75 76 77 78 79 80
      Theme(
        data: ThemeData(useMaterial3: false),
        child: const Directionality(
          textDirection: TextDirection.ltr,
          child: MaterialButton(
            onPressed: null,
            child: Text('button'),
          ),
81 82 83 84 85 86 87 88 89 90
        ),
      ),
    );
    material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 200));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, null);
    expect(material.elevation, 0.0);
91
    expect(material.shadowColor, null);
92
    expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))));
93 94 95 96
    expect(material.textStyle!.color, const Color(0x61000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
97
    expect(material.type, MaterialType.transparency);
98 99 100 101

    // Finish gesture to release resources.
    await gesture.up();
    await tester.pumpAndSettle();
102 103
  });

104
  testWidgetsWithLeakTracking('Does MaterialButton work with hover', (WidgetTester tester) async {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    const Color hoverColor = Color(0xff001122);

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          hoverColor: hoverColor,
          onPressed: () { },
          child: const Text('button'),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
    await gesture.addPointer();
    await gesture.moveTo(tester.getCenter(find.byType(MaterialButton)));
    await tester.pumpAndSettle();

    final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: hoverColor));
  });

127
  testWidgetsWithLeakTracking('Does MaterialButton work with focus', (WidgetTester tester) async {
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    const Color focusColor = Color(0xff001122);

    final FocusNode focusNode = FocusNode(debugLabel: 'MaterialButton Node');
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          focusColor: focusColor,
          focusNode: focusNode,
          onPressed: () { },
          child: const Text('button'),
        ),
      ),
    );

143
    FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
144 145 146 147 148
    focusNode.requestFocus();
    await tester.pumpAndSettle();

    final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: focusColor));
149 150

    focusNode.dispose();
151 152
  });

153
  testWidgetsWithLeakTracking('MaterialButton elevation and colors have proper precedence', (WidgetTester tester) async {
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
    const double elevation = 10.0;
    const double focusElevation = 11.0;
    const double hoverElevation = 12.0;
    const double highlightElevation = 13.0;
    const Color focusColor = Color(0xff001122);
    const Color hoverColor = Color(0xff112233);
    const Color highlightColor = Color(0xff223344);

    final Finder rawButtonMaterial = find.descendant(
      of: find.byType(MaterialButton),
      matching: find.byType(Material),
    );

    final FocusNode focusNode = FocusNode(debugLabel: 'MaterialButton Node');
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          focusColor: focusColor,
          hoverColor: hoverColor,
          highlightColor: highlightColor,
          elevation: elevation,
          focusElevation: focusElevation,
          hoverElevation: hoverElevation,
          highlightElevation: highlightElevation,
          focusNode: focusNode,
          onPressed: () { },
          child: const Text('button'),
        ),
      ),
    );
    await tester.pumpAndSettle();
186
    FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

    // Base elevation
    Material material = tester.widget<Material>(rawButtonMaterial);
    expect(material.elevation, equals(elevation));

    // Focus elevation overrides base
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    material = tester.widget<Material>(rawButtonMaterial);
    RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: focusColor));
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(material.elevation, equals(focusElevation));

    // Hover elevation overrides focus
202
    TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    await gesture.addPointer();
    addTearDown(() => gesture?.removePointer());
    await gesture.moveTo(tester.getCenter(find.byType(MaterialButton)));
    await tester.pumpAndSettle();
    material = tester.widget<Material>(rawButtonMaterial);
    inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: focusColor)..rect(color: hoverColor));
    expect(material.elevation, equals(hoverElevation));
    await gesture.removePointer();
    gesture = null;

    // Highlight elevation overrides hover
    final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(MaterialButton)));
    addTearDown(gesture2.removePointer);
    await tester.pumpAndSettle();
    material = tester.widget<Material>(rawButtonMaterial);
    inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: focusColor)..rect(color: highlightColor));
    expect(material.elevation, equals(highlightElevation));
    await gesture2.up();
223 224

    focusNode.dispose();
225 226
  });

227
  testWidgetsWithLeakTracking("MaterialButton's disabledColor takes precedence over its default disabled color.", (WidgetTester tester) async {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    // Regression test for https://github.com/flutter/flutter/issues/30012.

    final Finder rawButtonMaterial = find.descendant(
      of: find.byType(MaterialButton),
      matching: find.byType(Material),
    );

    await tester.pumpWidget(
      const Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          disabledColor: Color(0xff00ff00),
          onPressed: null,
          child: Text('button'),
        ),
      ),
    );

    final Material material = tester.widget<Material>(rawButtonMaterial);
    expect(material.color, const Color(0xff00ff00));
  });

250
  testWidgetsWithLeakTracking('Default MaterialButton meets a11y contrast guidelines', (WidgetTester tester) async {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: MaterialButton(
              child: const Text('MaterialButton'),
              onPressed: () { },
            ),
          ),
        ),
      ),
    );

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

    // Highlighted (pressed).
    final Offset center = tester.getCenter(find.byType(MaterialButton));
269
    final TestGesture gesture = await tester.startGesture(center);
270 271 272
    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));
273 274 275 276

    // Finish gesture to release resources.
    await gesture.up();
    await tester.pumpAndSettle();
277
  },
278
    skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
279
  );
280

281
  testWidgetsWithLeakTracking('MaterialButton gets focus when autofocus is set.', (WidgetTester tester) async {
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
    final FocusNode focusNode = FocusNode(debugLabel: 'MaterialButton');
    await tester.pumpWidget(
      MaterialApp(
        home: Center(
          child: MaterialButton(
            focusNode: focusNode,
            onPressed: () {},
            child: Container(width: 100, height: 100, color: const Color(0xffff0000)),
          ),
        ),
      ),
    );

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

    await tester.pumpWidget(
      MaterialApp(
        home: Center(
          child: MaterialButton(
            autofocus: true,
            focusNode: focusNode,
            onPressed: () {},
            child: Container(width: 100, height: 100, color: const Color(0xffff0000)),
          ),
        ),
      ),
    );
310

311 312
    await tester.pump();
    expect(focusNode.hasPrimaryFocus, isTrue);
313 314

    focusNode.dispose();
315
  });
316

317
  testWidgetsWithLeakTracking('MaterialButton onPressed and onLongPress callbacks are correctly called when non-null', (WidgetTester tester) async {
318 319 320 321

    bool wasPressed;
    Finder materialButton;

322
    Widget buildFrame({ VoidCallback? onPressed, VoidCallback? onLongPress }) {
323 324 325 326 327
      return Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          onPressed: onPressed,
          onLongPress: onLongPress,
328
          child: const Text('button'),
329 330 331 332 333 334 335
        ),
      );
    }

    // onPressed not null, onLongPress null.
    wasPressed = false;
    await tester.pumpWidget(
336
      buildFrame(onPressed: () { wasPressed = true; }),
337 338 339 340 341 342 343 344 345
    );
    materialButton = find.byType(MaterialButton);
    expect(tester.widget<MaterialButton>(materialButton).enabled, true);
    await tester.tap(materialButton);
    expect(wasPressed, true);

    // onPressed null, onLongPress not null.
    wasPressed = false;
    await tester.pumpWidget(
346
      buildFrame(onLongPress: () { wasPressed = true; }),
347 348 349 350 351 352 353 354
    );
    materialButton = find.byType(MaterialButton);
    expect(tester.widget<MaterialButton>(materialButton).enabled, true);
    await tester.longPress(materialButton);
    expect(wasPressed, true);

    // onPressed null, onLongPress null.
    await tester.pumpWidget(
355
      buildFrame(),
356 357 358 359 360
    );
    materialButton = find.byType(MaterialButton);
    expect(tester.widget<MaterialButton>(materialButton).enabled, false);
  });

361
  testWidgetsWithLeakTracking('MaterialButton onPressed and onLongPress callbacks are distinctly recognized', (WidgetTester tester) async {
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    bool didPressButton = false;
    bool didLongPressButton = false;

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          onPressed: () {
            didPressButton = true;
          },
          onLongPress: () {
            didLongPressButton = true;
          },
          child: const Text('button'),
        ),
      ),
    );

    final Finder materialButton = find.byType(MaterialButton);
    expect(tester.widget<MaterialButton>(materialButton).enabled, true);

    expect(didPressButton, isFalse);
    await tester.tap(materialButton);
    expect(didPressButton, isTrue);

    expect(didLongPressButton, isFalse);
    await tester.longPress(materialButton);
    expect(didLongPressButton, isTrue);
  });

392
  testWidgetsWithLeakTracking('MaterialButton changes mouse cursor when hovered', (WidgetTester tester) async {
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MouseRegion(
          cursor: SystemMouseCursors.forbidden,
          child: MaterialButton(
            onPressed: () {},
            mouseCursor: SystemMouseCursors.text,
          ),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: Offset.zero);

    await tester.pump();

411
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
412 413 414 415 416 417 418 419 420 421 422 423 424 425

    // Test default cursor
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MouseRegion(
          cursor: SystemMouseCursors.forbidden,
          child: MaterialButton(
            onPressed: () {},
          ),
        ),
      ),
    );

426
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
427 428 429 430 431 432 433 434 435 436 437 438 439 440

    // Test default cursor when disabled
    await tester.pumpWidget(
      const Directionality(
        textDirection: TextDirection.ltr,
        child: MouseRegion(
          cursor: SystemMouseCursors.forbidden,
          child: MaterialButton(
            onPressed: null,
          ),
        ),
      ),
    );

441
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
442 443
  });

444 445
  // This test is very similar to the '...explicit splashColor and highlightColor' test
  // in icon_button_test.dart. If you change this one, you may want to also change that one.
446
  testWidgetsWithLeakTracking('MaterialButton with explicit splashColor and highlightColor', (WidgetTester tester) async {
447 448 449
    const Color directSplashColor = Color(0xFF000011);
    const Color directHighlightColor = Color(0xFF000011);

450 451 452 453 454 455
    Widget buttonWidget = Center(
      child: MaterialButton(
        splashColor: directSplashColor,
        highlightColor: directHighlightColor,
        onPressed: () { /* to make sure the button is enabled */ },
        clipBehavior: Clip.antiAlias,
456 457 458 459 460 461 462 463
      ),
    );

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(
464
            useMaterial3: false,
465 466 467 468 469 470 471 472 473 474 475 476
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          child: buttonWidget,
        ),
      ),
    );

    final Offset center = tester.getCenter(find.byType(MaterialButton));
    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

477 478 479
    // Painter is translated to the center by the Center widget and not
    // the Material widget.
    const Rect expectedClipRect = Rect.fromLTRB(0.0, 0.0, 88.0, 36.0);
480 481 482 483 484 485
    final Path expectedClipPath = Path()
      ..addRRect(RRect.fromRectAndRadius(
          expectedClipRect,
          const Radius.circular(2.0),
      ));
    expect(
486
      Material.of(tester.element(find.byType(InkWell))),
487 488 489 490 491 492 493 494 495 496 497 498
      paints
        ..clipPath(pathMatcher: coversSameAreaAs(
            expectedClipPath,
            areaToCompare: expectedClipRect.inflate(10.0),
        ))
        ..circle(color: directSplashColor)
        ..rect(color: directHighlightColor),
    );

    const Color themeSplashColor1 = Color(0xFF001100);
    const Color themeHighlightColor1 = Color(0xFF001100);

499 500 501 502
    buttonWidget = Center(
      child: MaterialButton(
        onPressed: () { /* to make sure the button is enabled */ },
        clipBehavior: Clip.antiAlias,
503 504 505 506 507 508 509 510
      ),
    );

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(
511
            useMaterial3: false,
512 513 514 515 516 517 518 519 520 521
            highlightColor: themeHighlightColor1,
            splashColor: themeSplashColor1,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          child: buttonWidget,
        ),
      ),
    );

    expect(
522
      Material.of(tester.element(find.byType(InkWell))),
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
      paints
        ..clipPath(pathMatcher: coversSameAreaAs(
            expectedClipPath,
            areaToCompare: expectedClipRect.inflate(10.0),
        ))
        ..circle(color: themeSplashColor1)
        ..rect(color: themeHighlightColor1),
    );

    const Color themeSplashColor2 = Color(0xFF002200);
    const Color themeHighlightColor2 = Color(0xFF002200);

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(
540
            useMaterial3: false,
541 542 543 544 545 546 547 548 549 550
            highlightColor: themeHighlightColor2,
            splashColor: themeSplashColor2,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          child: buttonWidget, // same widget, so does not get updated because of us
        ),
      ),
    );

    expect(
551
      Material.of(tester.element(find.byType(InkWell))),
552 553 554 555 556 557 558 559
      paints
        ..circle(color: themeSplashColor2)
        ..rect(color: themeHighlightColor2),
    );

    await gesture.up();
  });

560
  testWidgetsWithLeakTracking('MaterialButton has no clip by default', (WidgetTester tester) async {
561
    final GlobalKey buttonKey = GlobalKey();
562 563 564 565
    final Widget buttonWidget = Center(
      child: MaterialButton(
        key: buttonKey,
        onPressed: () { /* to make sure the button is enabled */ },
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
      ),
    );

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          child: buttonWidget,
        ),
      ),
    );

    expect(
      tester.renderObject(find.byKey(buttonKey)),
      paintsExactlyCountTimes(#clipPath, 0),
    );
  });

587
  testWidgetsWithLeakTracking('Disabled MaterialButton has same semantic size as enabled and exposes disabled semantics', (WidgetTester tester) async {
588 589 590 591 592 593 594 595 596 597 598
    final SemanticsTester semantics = SemanticsTester(tester);

    const Rect expectedButtonSize = Rect.fromLTRB(0.0, 0.0, 116.0, 48.0);
    // Button is in center of screen
    final Matrix4 expectedButtonTransform = Matrix4.identity()
      ..translate(
        TestSemantics.fullScreen.width / 2 - expectedButtonSize.width /2,
        TestSemantics.fullScreen.height / 2 - expectedButtonSize.height /2,
      );

    // enabled button
599 600 601 602 603 604 605 606 607 608 609
    await tester.pumpWidget(
      Theme(
        data: ThemeData(useMaterial3: false),
        child: Directionality(
          textDirection: TextDirection.ltr,
          child: Center(
            child: MaterialButton(
              child: const Text('Button'),
              onPressed: () { /* to make sure the button is enabled */ },
            ),
          ),
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 635 636

    expect(semantics, hasSemantics(
      TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
            id: 1,
            rect: expectedButtonSize,
            transform: expectedButtonTransform,
            label: 'Button',
            actions: <SemanticsAction>[
              SemanticsAction.tap,
            ],
            flags: <SemanticsFlag>[
              SemanticsFlag.hasEnabledState,
              SemanticsFlag.isButton,
              SemanticsFlag.isEnabled,
              SemanticsFlag.isFocusable,
            ],
          ),
        ],
      ),
    ));

    // disabled button
637 638 639 640 641 642 643 644 645 646 647
    await tester.pumpWidget(
      Theme(
        data: ThemeData(useMaterial3: false),
        child: const Directionality(
          textDirection: TextDirection.ltr,
          child: Center(
            child: MaterialButton(
              onPressed: null, // button is disabled
              child: Text('Button'),
            ),
          ),
648 649
        ),
      ),
650
    );
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

    expect(semantics, hasSemantics(
      TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
            id: 1,
            rect: expectedButtonSize,
            transform: expectedButtonTransform,
            label: 'Button',
            flags: <SemanticsFlag>[
              SemanticsFlag.hasEnabledState,
              SemanticsFlag.isButton,
              SemanticsFlag.isFocusable,
            ],
          ),
        ],
      ),
    ));


    semantics.dispose();
672
  });
673

674
  testWidgetsWithLeakTracking('MaterialButton minWidth and height parameters', (WidgetTester tester) async {
675
    Widget buildFrame({ double? minWidth, double? height, EdgeInsets padding = EdgeInsets.zero, Widget? child }) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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 735 736 737 738 739 740
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
          child: MaterialButton(
            padding: padding,
            minWidth: minWidth,
            height: height,
            onPressed: null,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            child: child,
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame(minWidth: 8.0, height: 24.0));
    expect(tester.getSize(find.byType(MaterialButton)), const Size(8.0, 24.0));

    await tester.pumpWidget(buildFrame(minWidth: 8.0));
    // Default minHeight constraint is 36, see RawMaterialButton.
    expect(tester.getSize(find.byType(MaterialButton)), const Size(8.0, 36.0));

    await tester.pumpWidget(buildFrame(height: 8.0));
    // Default minWidth constraint is 88, see RawMaterialButton.
    expect(tester.getSize(find.byType(MaterialButton)), const Size(88.0, 8.0));

    await tester.pumpWidget(buildFrame());
    expect(tester.getSize(find.byType(MaterialButton)), const Size(88.0, 36.0));

    await tester.pumpWidget(buildFrame(padding: const EdgeInsets.all(4.0)));
    expect(tester.getSize(find.byType(MaterialButton)), const Size(88.0, 36.0));

    // Size is defined by the padding.
    await tester.pumpWidget(
      buildFrame(
        minWidth: 0.0,
        height: 0.0,
        padding: const EdgeInsets.all(4.0),
      ),
    );
    expect(tester.getSize(find.byType(MaterialButton)), const Size(8.0, 8.0));

    // Size is defined by the padded child.
    await tester.pumpWidget(
      buildFrame(
        minWidth: 0.0,
        height: 0.0,
        padding: const EdgeInsets.all(4.0),
        child: const SizedBox(width: 8.0, height: 8.0),
      ),
    );
    expect(tester.getSize(find.byType(MaterialButton)), const Size(16.0, 16.0));

    // Size is defined by the minWidth, height constraints.
    await tester.pumpWidget(
      buildFrame(
        minWidth: 18.0,
        height: 18.0,
        padding: const EdgeInsets.all(4.0),
        child: const SizedBox(width: 8.0, height: 8.0),
      ),
    );
    expect(tester.getSize(find.byType(MaterialButton)), const Size(18.0, 18.0));
  });

741
  testWidgetsWithLeakTracking('MaterialButton size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
742 743 744 745 746 747
    final Key key1 = UniqueKey();
    await tester.pumpWidget(
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded),
        child: Directionality(
          textDirection: TextDirection.ltr,
748 749 750 751 752
          child: Center(
            child: MaterialButton(
              key: key1,
              child: const SizedBox(width: 50.0, height: 8.0),
              onPressed: () { },
753 754 755 756 757 758 759 760 761 762 763 764 765 766
            ),
          ),
        ),
      ),
    );

    expect(tester.getSize(find.byKey(key1)), const Size(88.0, 48.0));

    final Key key2 = UniqueKey();
    await tester.pumpWidget(
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
        child: Directionality(
          textDirection: TextDirection.ltr,
767 768 769 770 771
          child: Center(
            child: MaterialButton(
              key: key2,
              child: const SizedBox(width: 50.0, height: 8.0),
              onPressed: () { },
772 773 774 775 776 777 778 779 780
            ),
          ),
        ),
      ),
    );

    expect(tester.getSize(find.byKey(key2)), const Size(88.0, 36.0));
  });

781
  testWidgetsWithLeakTracking('MaterialButton shape overrides ButtonTheme shape', (WidgetTester tester) async {
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    // Regression test for https://github.com/flutter/flutter/issues/29146
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          onPressed: () { },
          shape: const StadiumBorder(),
          child: const Text('button'),
        ),
      ),
    );

    final Finder rawButtonMaterial = find.descendant(
      of: find.byType(MaterialButton),
      matching: find.byType(Material),
    );
    expect(tester.widget<Material>(rawButtonMaterial).shape, const StadiumBorder());
  });
800

801
  testWidgetsWithLeakTracking('MaterialButton responds to density changes.', (WidgetTester tester) async {
802
    const Key key = Key('test');
803
    const Key childKey = Key('test child');
804 805

    Future<void> buildTest(VisualDensity visualDensity, {bool useText = false}) async {
806
      return tester.pumpWidget(
807
        MaterialApp(
808
          theme: ThemeData(useMaterial3: false),
809 810 811 812 813 814 815
          home: Directionality(
            textDirection: TextDirection.rtl,
            child: Center(
              child: MaterialButton(
                visualDensity: visualDensity,
                key: key,
                onPressed: () {},
816
                child: useText ? const Text('Text', key: childKey) : Container(key: childKey, width: 100, height: 100, color: const Color(0xffff0000)),
817 818 819 820 821 822 823
              ),
            ),
          ),
        ),
      );
    }

824
    await buildTest(VisualDensity.standard);
825
    final RenderBox box = tester.renderObject(find.byKey(key));
826
    Rect childRect = tester.getRect(find.byKey(childKey));
827 828
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(132, 100)));
829
    expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
830 831 832

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
    await tester.pumpAndSettle();
833
    childRect = tester.getRect(find.byKey(childKey));
834
    expect(box.size, equals(const Size(156, 124)));
835
    expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
836 837 838

    await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
    await tester.pumpAndSettle();
839
    childRect = tester.getRect(find.byKey(childKey));
840
    expect(box.size, equals(const Size(108, 100)));
841
    expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
842

843
    await buildTest(VisualDensity.standard, useText: true);
844
    await tester.pumpAndSettle();
845
    childRect = tester.getRect(find.byKey(childKey));
846
    expect(box.size, equals(const Size(88, 48)));
847
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
848 849 850

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0), useText: true);
    await tester.pumpAndSettle();
851
    childRect = tester.getRect(find.byKey(childKey));
852
    expect(box.size, equals(const Size(112, 60)));
853
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
854 855 856

    await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0), useText: true);
    await tester.pumpAndSettle();
857
    childRect = tester.getRect(find.byKey(childKey));
858
    expect(box.size, equals(const Size(76, 36)));
859
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
860
  });
861

862
  testWidgetsWithLeakTracking('disabledElevation is passed to RawMaterialButton', (WidgetTester tester) async {
863 864 865
    const double disabledElevation = 16;

    final Finder rawMaterialButtonFinder = find.descendant(
866 867
      of: find.byType(MaterialButton),
      matching: find.byType(RawMaterialButton),
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    );

    await tester.pumpWidget(
      const Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          disabledElevation: disabledElevation,
          onPressed: null, // disabled button
          child: Text('button'),
        ),
      ),
    );

    final RawMaterialButton rawMaterialButton = tester.widget(rawMaterialButtonFinder);
    expect(rawMaterialButton.disabledElevation, equals(disabledElevation));
  });

885
  testWidgetsWithLeakTracking('MaterialButton.disabledElevation defaults to 0.0 when not provided', (WidgetTester tester) async {
886
    final Finder rawMaterialButtonFinder = find.descendant(
887 888
      of: find.byType(MaterialButton),
      matching: find.byType(RawMaterialButton),
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    );

    await tester.pumpWidget(
      const Directionality(
        textDirection: TextDirection.ltr,
        child: MaterialButton(
          onPressed: null, // disabled button
          child: Text('button'),
        ),
      ),
    );

    final RawMaterialButton rawMaterialButton = tester.widget(rawMaterialButtonFinder);
    expect(rawMaterialButton.disabledElevation, equals(0.0));
  });
904
}