outline_button_test.dart 42 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 10 11 12 13

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

void main() {
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
  testWidgets('OutlineButton defaults', (WidgetTester tester) async {
    final Finder rawButtonMaterial = find.descendant(
      of: find.byType(OutlineButton),
      matching: find.byType(Material),
    );

    // Enabled OutlineButton
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: OutlineButton(
          onPressed: () { },
          child: const Text('button'),
        ),
      ),
    );
    Material material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 75));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, const Color(0x00000000));
    expect(material.elevation, 0.0);
37
    expect(material.shadowColor, null);
38 39 40 41
    expect(material.textStyle!.color, const Color(0xdd000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
42 43 44 45 46 47 48 49 50 51 52 53 54 55
    expect(material.type, MaterialType.button);

    final Offset center = tester.getCenter(find.byType(OutlineButton));
    await tester.startGesture(center);
    await tester.pumpAndSettle();

    // No change vs enabled and not pressed.
    material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 75));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, const Color(0x00000000));
    expect(material.elevation, 0.0);
56
    expect(material.shadowColor, null);
57 58 59 60
    expect(material.textStyle!.color, const Color(0xdd000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    expect(material.type, MaterialType.button);

    // Disabled OutlineButton
    await tester.pumpWidget(
      const Directionality(
        textDirection: TextDirection.ltr,
        child: OutlineButton(
          onPressed: null,
          child: Text('button'),
        ),
      ),
    );
    material = tester.widget<Material>(rawButtonMaterial);
    expect(material.animationDuration, const Duration(milliseconds: 75));
    expect(material.borderOnForeground, true);
    expect(material.borderRadius, null);
    expect(material.clipBehavior, Clip.none);
    expect(material.color, const Color(0x00000000));
    expect(material.elevation, 0.0);
80
    expect(material.shadowColor, null);
81 82 83 84
    expect(material.textStyle!.color, const Color(0x61000000));
    expect(material.textStyle!.fontFamily, 'Roboto');
    expect(material.textStyle!.fontSize, 14);
    expect(material.textStyle!.fontWeight, FontWeight.w500);
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    expect(material.type, MaterialType.button);
  });

  testWidgets('Does OutlineButton work with hover', (WidgetTester tester) async {
    const Color hoverColor = Color(0xff001122);

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: OutlineButton(
          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(OutlineButton)));
    await tester.pumpAndSettle();
    final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
    expect(inkFeatures, paints..rect(color: hoverColor));

109
    await gesture.removePointer();
110 111
  });

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  testWidgets('OutlineButton changes mouse cursor when hovered', (WidgetTester tester) async {
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MouseRegion(
          cursor: SystemMouseCursors.forbidden,
          child: OutlineButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Hello'),
            onPressed: () {},
            mouseCursor: SystemMouseCursors.text,
          ),
        ),
      ),
    );

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

    await tester.pump();
133
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
134 135 136 137 138 139 140 141 142 143 144 145 146 147

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: MouseRegion(
          cursor: SystemMouseCursors.forbidden,
          child: OutlineButton(
            onPressed: () {},
            mouseCursor: SystemMouseCursors.text,
          ),
        ),
      ),
    );

148
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
149 150 151 152 153 154 155 156 157 158 159 160 161 162

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

163
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
164 165 166 167 168 169 170 171 172 173 174 175 176 177

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

178
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
179 180
  });

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  testWidgets('Does OutlineButton work with focus', (WidgetTester tester) async {
    const Color focusColor = Color(0xff001122);

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

    FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    focusNode.requestFocus();
    await tester.pumpAndSettle();

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

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  testWidgets('Does OutlineButton work with autofocus', (WidgetTester tester) async {
    const Color focusColor = Color(0xff001122);

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

    FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    await tester.pumpAndSettle();

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

229 230 231
  testWidgets('OutlineButton implements debugFillProperties', (WidgetTester tester) async {
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    OutlineButton(
232
      onPressed: () {},
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
      textColor: const Color(0xFF00FF00),
      disabledTextColor: const Color(0xFFFF0000),
      color: const Color(0xFF000000),
      highlightColor: const Color(0xFF1565C0),
      splashColor: const Color(0xFF9E9E9E),
      child: const Text('Hello'),
    ).debugFillProperties(builder);

    final List<String> description = builder.properties
      .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
      .map((DiagnosticsNode node) => node.toString()).toList();

    expect(description, <String>[
      'textColor: Color(0xff00ff00)',
      'disabledTextColor: Color(0xffff0000)',
      'color: Color(0xff000000)',
      'highlightColor: Color(0xff1565c0)',
      'splashColor: Color(0xff9e9e9e)',
    ]);
  });

  testWidgets('Default OutlineButton meets a11y contrast guidelines', (WidgetTester tester) async {
255 256
    final FocusNode focusNode = FocusNode();

257 258 259 260 261
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
262
              onPressed: () {},
263
              focusNode: focusNode,
264
              child: const Text('OutlineButton'),
265 266 267 268 269 270 271 272 273
            ),
          ),
        ),
      ),
    );

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

274 275 276 277 278 279 280 281 282 283 284
    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    // Hovered.
    final Offset center = tester.getCenter(find.byType(OutlineButton));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
285
    addTearDown(gesture.removePointer);
286 287 288 289
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    await expectLater(tester, meetsGuideline(textContrastGuideline));

290
    // Highlighted (pressed).
291 292 293 294 295
    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));
  },
296
    skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    semanticsEnabled: true,
  );

  testWidgets('OutlineButton with colored theme meets a11y contrast guidelines', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();

    final ColorScheme colorScheme = ColorScheme.fromSwatch(primarySwatch: Colors.blue);

    Color getTextColor(Set<MaterialState> states) {
      final Set<MaterialState> interactiveStates = <MaterialState>{
        MaterialState.pressed,
        MaterialState.hovered,
        MaterialState.focused,
      };
      if (states.any(interactiveStates.contains)) {
312
        return Colors.blue[900]!;
313
      }
314
      return Colors.blue[800]!;
315 316 317 318 319 320 321 322 323 324 325 326 327
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: ButtonTheme(
              colorScheme: colorScheme,
              textTheme: ButtonTextTheme.primary,
              child: OutlineButton(
                onPressed: () {},
                focusNode: focusNode,
                textColor: MaterialStateColor.resolveWith(getTextColor),
328
                child: const Text('OutlineButton'),
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
              ),
            ),
          ),
        ),
      ),
    );

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

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

    // Hovered.
345
    final Offset center = tester.getCenter(find.byType(OutlineButton));
346 347 348 349
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
350
    addTearDown(gesture.removePointer);
351 352 353 354 355 356
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    await expectLater(tester, meetsGuideline(textContrastGuideline));

    // Highlighted (pressed).
    await gesture.down(center);
357 358 359 360
    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));
  },
361
    skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
362 363
    semanticsEnabled: true,
  );
364

365 366 367
  testWidgets('OutlineButton uses stateful color for text color in different states', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();

368 369 370 371
    const Color pressedColor = Color(0x00000001);
    const Color hoverColor = Color(0x00000002);
    const Color focusedColor = Color(0x00000003);
    const Color defaultColor = Color(0x00000004);
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

    Color getTextColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return pressedColor;
      }
      if (states.contains(MaterialState.hovered)) {
        return hoverColor;
      }
      if (states.contains(MaterialState.focused)) {
        return focusedColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              onPressed: () {},
              focusNode: focusNode,
              textColor: MaterialStateColor.resolveWith(getTextColor),
394
              child: const Text('OutlineButton'),
395 396 397 398 399 400
            ),
          ),
        ),
      ),
    );

401 402
    Color? textColor() {
      return tester.renderObject<RenderParagraph>(find.text('OutlineButton')).text.style!.color;
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    }

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

    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    expect(textColor(), focusedColor);

    // Hovered.
    final Offset center = tester.getCenter(find.byType(OutlineButton));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
419
    addTearDown(gesture.removePointer);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    expect(textColor(), 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(textColor(), pressedColor);
  });

  testWidgets('OutlineButton uses stateful color for icon color in different states', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();
    final Key buttonKey = UniqueKey();

435 436 437 438
    const Color pressedColor = Color(0x00000001);
    const Color hoverColor = Color(0x00000002);
    const Color focusedColor = Color(0x00000003);
    const Color defaultColor = Color(0x00000004);
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

    Color getTextColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return pressedColor;
      }
      if (states.contains(MaterialState.hovered)) {
        return hoverColor;
      }
      if (states.contains(MaterialState.focused)) {
        return focusedColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton.icon(
              key: buttonKey,
              icon: const Icon(Icons.add),
              label: const Text('OutlineButton'),
              onPressed: () {},
              focusNode: focusNode,
              textColor: MaterialStateColor.resolveWith(getTextColor),
            ),
          ),
        ),
      ),
    );

470
    Color? iconColor() => _iconStyle(tester, Icons.add).color;
471 472 473 474 475 476 477 478 479 480 481 482 483 484
    // Default, not disabled.
    expect(iconColor(), equals(defaultColor));

    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    expect(iconColor(), focusedColor);

    // Hovered.
    final Offset center = tester.getCenter(find.byKey(buttonKey));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
485
    addTearDown(gesture.removePointer);
486 487 488 489 490 491 492 493 494 495 496 497 498 499
    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('OutlineButton ignores disabled text color if text color is stateful', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();

500 501 502
    const Color disabledColor = Color(0x00000001);
    const Color defaultColor = Color(0x00000002);
    const Color unusedDisabledTextColor = Color(0x00000003);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

    Color getTextColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return disabledColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              onPressed: null,
              focusNode: focusNode,
              textColor: MaterialStateColor.resolveWith(getTextColor),
              disabledTextColor: unusedDisabledTextColor,
520
              child: const Text('OutlineButton'),
521 522 523 524 525 526
            ),
          ),
        ),
      ),
    );

527 528
    Color? textColor() {
      return tester.renderObject<RenderParagraph>(find.text('OutlineButton')).text.style!.color;
529 530 531 532 533 534 535
    }

    // Disabled.
    expect(textColor(), equals(disabledColor));
    expect(textColor(), isNot(unusedDisabledTextColor));
  });

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
  testWidgets('OutlineButton uses stateful color for border color in different states', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode();

    const Color pressedColor = Color(0x00000001);
    const Color hoverColor = Color(0x00000002);
    const Color focusedColor = Color(0x00000003);
    const Color defaultColor = Color(0x00000004);

    Color getBorderColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return pressedColor;
      }
      if (states.contains(MaterialState.hovered)) {
        return hoverColor;
      }
      if (states.contains(MaterialState.focused)) {
        return focusedColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              onPressed: () {},
              focusNode: focusNode,
              borderSide: BorderSide(color: MaterialStateColor.resolveWith(getBorderColor)),
565
              child: const Text('OutlineButton'),
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
            ),
          ),
        ),
      ),
    );

    final Finder outlineButton = find.byType(OutlineButton);

    // Default, not disabled.
    expect(outlineButton, paints..path(color: defaultColor));

    // Focused.
    focusNode.requestFocus();
    await tester.pumpAndSettle();
    expect(outlineButton, paints..path(color: focusedColor));

    // Hovered.
    final Offset center = tester.getCenter(find.byType(OutlineButton));
    final TestGesture gesture = await tester.createGesture(
      kind: PointerDeviceKind.mouse,
    );
    await gesture.addPointer();
588
    addTearDown(gesture.removePointer);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    await gesture.moveTo(center);
    await tester.pumpAndSettle();
    expect(outlineButton, paints..path(color: hoverColor));

    // Highlighted (pressed).
    await gesture.down(center);
    await tester.pumpAndSettle();
    expect(outlineButton, paints..path(color: pressedColor));
  });

  testWidgets('OutlineButton ignores highlightBorderColor if border color is stateful', (WidgetTester tester) async {
    const Color pressedColor = Color(0x00000001);
    const Color defaultColor = Color(0x00000002);
    const Color ignoredPressedColor = Color(0x00000003);

    Color getBorderColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return pressedColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              onPressed: () {},
              borderSide: BorderSide(color: MaterialStateColor.resolveWith(getBorderColor)),
              highlightedBorderColor: ignoredPressedColor,
619
              child: const Text('OutlineButton'),
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
            ),
          ),
        ),
      ),
    );

    final Finder outlineButton = find.byType(OutlineButton);

    // Default, not disabled.
    expect(outlineButton, paints..path(color: defaultColor));

    // Highlighted (pressed).
    await tester.press(outlineButton);
    await tester.pumpAndSettle();
    expect(outlineButton, paints..path(color: pressedColor));
  });

  testWidgets('OutlineButton ignores disabledBorderColor if border color is stateful', (WidgetTester tester) async {
    const Color disabledColor = Color(0x00000001);
    const Color defaultColor = Color(0x00000002);
    const Color ignoredDisabledColor = Color(0x00000003);

    Color getBorderColor(Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return disabledColor;
      }
      return defaultColor;
    }

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              onPressed: null,
              borderSide: BorderSide(color: MaterialStateColor.resolveWith(getBorderColor)),
              highlightedBorderColor: ignoredDisabledColor,
657
              child: const Text('OutlineButton'),
658 659 660 661 662 663 664 665 666 667
            ),
          ),
        ),
      ),
    );

    // Disabled.
    expect(find.byType(OutlineButton), paints..path(color: disabledColor));
  });

668
  testWidgets('OutlineButton onPressed and onLongPress callbacks are correctly called when non-null', (WidgetTester tester) async {
669

670 671 672
    bool wasPressed;
    Finder outlineButton;

673
    Widget buildFrame({ VoidCallback? onPressed, VoidCallback? onLongPress }) {
674
      return Directionality(
675
        textDirection: TextDirection.ltr,
676 677 678
        child: OutlineButton(
          onPressed: onPressed,
          onLongPress: onLongPress,
679
          child: const Text('button'),
680 681 682 683
        ),
      );
    }

684 685
    // onPressed not null, onLongPress null.
    wasPressed = false;
686
    await tester.pumpWidget(
687
      buildFrame(onPressed: () { wasPressed = true; }, onLongPress: null),
688
    );
689 690 691 692
    outlineButton = find.byType(OutlineButton);
    expect(tester.widget<OutlineButton>(outlineButton).enabled, true);
    await tester.tap(outlineButton);
    expect(wasPressed, true);
693

694 695
    // onPressed null, onLongPress not null.
    wasPressed = false;
696
    await tester.pumpWidget(
697
      buildFrame(onPressed: null, onLongPress: () { wasPressed = true; }),
698
    );
699 700 701 702 703 704 705 706 707 708
    outlineButton = find.byType(OutlineButton);
    expect(tester.widget<OutlineButton>(outlineButton).enabled, true);
    await tester.longPress(outlineButton);
    expect(wasPressed, true);

    // onPressed null, onLongPress null.
    await tester.pumpWidget(
      buildFrame(onPressed: null, onLongPress: null),
    );
    outlineButton = find.byType(OutlineButton);
709 710 711
    expect(tester.widget<OutlineButton>(outlineButton).enabled, false);
  });

712
  testWidgets("Outline button doesn't crash if disabled during a gesture", (WidgetTester tester) async {
713
    Widget buildFrame(VoidCallback? onPressed) {
714 715 716 717 718 719 720 721 722 723 724
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(),
          child: Center(
            child: OutlineButton(onPressed: onPressed),
          ),
        ),
      );
    }

725
    await tester.pumpWidget(buildFrame(() {}));
726 727 728 729 730
    await tester.press(find.byType(OutlineButton));
    await tester.pumpAndSettle();
    await tester.pumpWidget(buildFrame(null));
    await tester.pumpAndSettle();
  });
731

732
  testWidgets('OutlineButton shape and border component overrides', (WidgetTester tester) async {
733 734 735
    const Color fillColor = Color(0xFF00FF00);
    const Color borderColor = Color(0xFFFF0000);
    const Color highlightedBorderColor = Color(0xFF0000FF);
736
    const Color disabledBorderColor = Color(0xFFFF00FF);
737 738
    const double borderWidth = 4.0;

739
    Widget buildFrame({ VoidCallback? onPressed }) {
740
      return Directionality(
741
        textDirection: TextDirection.ltr,
742 743 744
        child: Theme(
          data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
          child: Container(
745
            alignment: Alignment.topLeft,
746
            child: OutlineButton(
747
              shape: const RoundedRectangleBorder(), // default border radius is 0
748
              clipBehavior: Clip.antiAlias,
749
              color: fillColor,
750 751 752 753
              // Causes the button to be filled with the theme's canvasColor
              // instead of Colors.transparent before the button material's
              // elevation is animated to 2.0.
              highlightElevation: 2.0,
754
              highlightedBorderColor: highlightedBorderColor,
755
              disabledBorderColor: disabledBorderColor,
756 757 758 759
              borderSide: const BorderSide(
                width: borderWidth,
                color: borderColor,
              ),
760 761
              onPressed: onPressed,
              child: const Text('button'),
762 763 764
            ),
          ),
        ),
765 766
      );
    }
767

Dan Field's avatar
Dan Field committed
768
    const Rect clipRect = Rect.fromLTRB(0.0, 0.0, 116.0, 36.0);
769
    final Path clipPath = Path()..addRect(clipRect);
770 771 772 773 774 775 776 777 778 779 780

    final Finder outlineButton = find.byType(OutlineButton);

    // Pump a button with a null onPressed callback to make it disabled.
    await tester.pumpWidget(
      buildFrame(onPressed: null),
    );

    // Expect that the button is disabled and painted with the disabled border color.
    expect(tester.widget<OutlineButton>(outlineButton).enabled, false);
    expect(
781
      outlineButton,
782 783
      paints..path(color: disabledBorderColor, strokeWidth: borderWidth),
    );
784
    _checkPhysicalLayer(
785
      tester.element(outlineButton),
786
      const Color(0x00000000),
787 788 789
      clipPath: clipPath,
      clipRect: clipRect,
    );
790 791 792

    // Pump a new button with a no-op onPressed callback to make it enabled.
    await tester.pumpWidget(
793
      buildFrame(onPressed: () {}),
794 795 796 797 798
    );

    // Wait for the border color to change from disabled to enabled.
    await tester.pumpAndSettle();

799
    // Expect that the button is enabled and painted with the enabled border color.
800
    expect(tester.widget<OutlineButton>(outlineButton).enabled, true);
801 802
    expect(
      outlineButton,
803 804
      paints..path(color: borderColor, strokeWidth: borderWidth),
    );
805
    // initially, the interior of the button is transparent
806
    _checkPhysicalLayer(
807 808 809 810 811
      tester.element(outlineButton),
      fillColor.withAlpha(0x00),
      clipPath: clipPath,
      clipRect: clipRect,
    );
812 813 814 815 816 817 818 819 820

    final Offset center = tester.getCenter(outlineButton);
    final TestGesture gesture = await tester.startGesture(center);
    await tester.pump(); // start gesture
    // Wait for the border's color to change to highlightedBorderColor and
    // the fillColor to become opaque.
    await tester.pump(const Duration(milliseconds: 200));
    expect(
      outlineButton,
821 822
      paints..path(color: highlightedBorderColor, strokeWidth: borderWidth),
    );
823
    _checkPhysicalLayer(
824 825 826 827 828
      tester.element(outlineButton),
      fillColor.withAlpha(0xFF),
      clipPath: clipPath,
      clipRect: clipRect,
    );
829 830 831 832 833 834

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
    expect(
      outlineButton,
835 836
      paints..path(color: borderColor, strokeWidth: borderWidth),
    );
837
    _checkPhysicalLayer(
838 839 840 841 842
      tester.element(outlineButton),
      fillColor.withAlpha(0x00),
      clipPath: clipPath,
      clipRect: clipRect,
    );
843
  });
844

845
  testWidgets('OutlineButton has no clip by default', (WidgetTester tester) async {
846
    final GlobalKey buttonKey = GlobalKey();
847
    await tester.pumpWidget(
848
      Directionality(
849
        textDirection: TextDirection.ltr,
850 851 852
        child: Material(
          child: Center(
            child: OutlineButton(
853 854 855
              key: buttonKey,
              onPressed: () {},
              child: const Text('ABC'),
856 857 858 859 860 861 862
            ),
          ),
        ),
      ),
    );

    expect(
863 864
      tester.renderObject(find.byKey(buttonKey)),
      paintsExactlyCountTimes(#clipPath, 0),
865
    );
866
  });
867

868
  testWidgets('OutlineButton contributes semantics', (WidgetTester tester) async {
869
    final SemanticsTester semantics = SemanticsTester(tester);
870
    await tester.pumpWidget(
871
      Directionality(
872
        textDirection: TextDirection.ltr,
873 874 875
        child: Material(
          child: Center(
            child: OutlineButton(
876
              onPressed: () {},
877
              child: const Text('ABC'),
878 879 880 881 882 883 884
            ),
          ),
        ),
      ),
    );

    expect(semantics, hasSemantics(
885
      TestSemantics.root(
886
        children: <TestSemantics>[
887
          TestSemantics.rootChild(
888 889 890 891
            actions: <SemanticsAction>[
              SemanticsAction.tap,
            ],
            label: 'ABC',
Dan Field's avatar
Dan Field committed
892
            rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
893
            transform: Matrix4.translationValues(356.0, 276.0, 0.0),
894 895
            flags: <SemanticsFlag>[
              SemanticsFlag.hasEnabledState,
896
              SemanticsFlag.isButton,
897
              SemanticsFlag.isEnabled,
898
              SemanticsFlag.isFocusable,
899
            ],
900
          ),
901 902 903 904 905 906 907 908 909 910
        ],
      ),
      ignoreId: true,
    ));

    semantics.dispose();
  });

  testWidgets('OutlineButton scales textScaleFactor', (WidgetTester tester) async {
    await tester.pumpWidget(
911
      Directionality(
912
        textDirection: TextDirection.ltr,
913 914
        child: Material(
          child: MediaQuery(
915
            data: const MediaQueryData(textScaleFactor: 1.0),
916 917
            child: Center(
              child: OutlineButton(
918
                onPressed: () {},
919 920 921 922 923 924 925 926
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

927
    expect(tester.getSize(find.byType(OutlineButton)), equals(const Size(88.0, 48.0)));
928 929 930 931
    expect(tester.getSize(find.byType(Text)), equals(const Size(42.0, 14.0)));

    // textScaleFactor expands text, but not button.
    await tester.pumpWidget(
932
      Directionality(
933
        textDirection: TextDirection.ltr,
934 935
        child: Material(
          child: MediaQuery(
936
            data: const MediaQueryData(textScaleFactor: 1.3),
937 938
            child: Center(
              child: FlatButton(
939
                onPressed: () {},
940 941 942 943 944 945 946 947
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

948
    expect(tester.getSize(find.byType(FlatButton)), equals(const Size(88.0, 48.0)));
949
    // Scaled text rendering is different on Linux and Mac by one pixel.
950
    // TODO(gspencergoog): Figure out why this is, and fix it. https://github.com/flutter/flutter/issues/12357
951 952 953 954 955
    expect(tester.getSize(find.byType(Text)).width, isIn(<double>[54.0, 55.0]));
    expect(tester.getSize(find.byType(Text)).height, isIn(<double>[18.0, 19.0]));

    // Set text scale large enough to expand text and button.
    await tester.pumpWidget(
956
      Directionality(
957
        textDirection: TextDirection.ltr,
958 959
        child: Material(
          child: MediaQuery(
960
            data: const MediaQueryData(textScaleFactor: 3.0),
961 962
            child: Center(
              child: FlatButton(
963
                onPressed: () {},
964 965 966 967 968 969 970 971 972
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

    // Scaled text rendering is different on Linux and Mac by one pixel.
973
    // TODO(gspencergoog): Figure out why this is, and fix it. https://github.com/flutter/flutter/issues/12357
974
    expect(tester.getSize(find.byType(FlatButton)).width, isIn(<double>[158.0, 159.0]));
975
    expect(tester.getSize(find.byType(FlatButton)).height, equals(48.0));
976 977
    expect(tester.getSize(find.byType(Text)).width, isIn(<double>[126.0, 127.0]));
    expect(tester.getSize(find.byType(Text)).height, equals(42.0));
978
  });
979

980 981 982 983 984 985 986
  testWidgets('OutlineButton pressed fillColor default', (WidgetTester tester) async {
    Widget buildFrame(ThemeData theme) {
      return MaterialApp(
        theme: theme,
        home: Scaffold(
          body: Center(
            child: OutlineButton(
987
              onPressed: () {},
988 989 990 991
              // Causes the button to be filled with the theme's canvasColor
              // instead of Colors.transparent before the button material's
              // elevation is animated to 2.0.
              highlightElevation: 2.0,
992 993 994 995 996 997 998 999 1000
              child: const Text('Hello'),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame(ThemeData.dark()));
    final Finder button = find.byType(OutlineButton);
1001
    final Element buttonElement = tester.element(button);
1002 1003 1004 1005
    final Offset center = tester.getCenter(button);

    // Default value for dark Theme.of(context).canvasColor as well as
    // the OutlineButton fill color when the button has been pressed.
1006
    Color fillColor = Colors.grey[850]!;
1007 1008

    // Initially the interior of the button is transparent.
1009
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
1010 1011 1012 1013 1014

    // Tap-press gesture on the button triggers the fill animation.
    TestGesture gesture = await tester.startGesture(center);
    await tester.pump(); // Start the button fill animation.
    await tester.pump(const Duration(milliseconds: 200)); // Animation is complete.
1015
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0xFF));
1016 1017 1018 1019

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
1020
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
1021 1022 1023 1024 1025 1026

    await tester.pumpWidget(buildFrame(ThemeData.light()));
    await tester.pumpAndSettle(); // Finish the theme change animation.

    // Default value for light Theme.of(context).canvasColor as well as
    // the OutlineButton fill color when the button has been pressed.
1027
    fillColor = Colors.grey[50]!;
1028 1029

    // Initially the interior of the button is transparent.
1030
    // expect(button, paints..path(color: fillColor.withAlpha(0x00)));
1031 1032 1033 1034 1035

    // Tap-press gesture on the button triggers the fill animation.
    gesture = await tester.startGesture(center);
    await tester.pump(); // Start the button fill animation.
    await tester.pump(const Duration(milliseconds: 200)); // Animation is complete.
1036
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0xFF));
1037 1038 1039 1040

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
1041
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
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 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  testWidgets('OutlineButton respects the provided materialTapTargetSize', (WidgetTester tester) async {
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Center(
            child: OutlineButton(
              materialTapTargetSize: MaterialTapTargetSize.padded,
              onPressed: () {},
              child: const SizedBox(width: 50.0, height: 8.0),
            ),
          ),
        ),
      ),
    );

    // Default Width of OutlineButton with MaterialTapTargetSize (88)
    expect(tester.getSize(find.byType(OutlineButton)), const Size(88.0, 48.0));

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Center(
            child: OutlineButton(
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              onPressed: () {},
              child: const SizedBox(width: 50.0, height: 8.0),
            ),
          ),
        ),
      ),
    );

    // Default Width of OutlineButton with MaterialTapTargetSize (88)
    expect(tester.getSize(find.byType(OutlineButton)), const Size(88.0, 36.0));

    final LocalKey key1 = UniqueKey();
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Center(
            child: OutlineButton.icon(
              key: key1,
              materialTapTargetSize: MaterialTapTargetSize.padded,
              icon: const Icon(Icons.add_alarm),
              label: const SizedBox(width: 50.0, height: 8.0),
              onPressed: () { },
            ),
          ),
        ),
      ),
    );

    final Size addAlarmIconSize = tester.getSize(find.byIcon(Icons.add_alarm));

    // The expected width is the sum of:
    // the width of the icon
    // the gap between the icon and the label (8)
    // the width of the label (50)
    // the horizontal padding: start (12), end (16)
    expect(tester.getSize(find.byKey(key1)), Size(86 + addAlarmIconSize.width, 48.0));

    final LocalKey key2 = UniqueKey();
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Center(
            child: OutlineButton.icon(
              key: key2,
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              icon: const Icon(Icons.add),
              label: const SizedBox(width: 50.0, height: 8.0),
              onPressed: () { },
            ),
          ),
        ),
      ),
    );

    // The expected width is the sum of:
    // the width of the icon
    // the gap between the icon and the label (8)
    // the width of the label (50)
    // the horizontal padding: start (12), end (16)
    final Size addIconSize = tester.getSize(find.byIcon(Icons.add));
    expect(tester.getSize(find.byKey(key2)), Size(86 + addIconSize.width, 36.0));
  });

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
  testWidgets('OutlineButton onPressed and onLongPress callbacks are distinctly recognized', (WidgetTester tester) async {
    bool didPressButton = false;
    bool didLongPressButton = false;

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

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

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

    expect(didLongPressButton, isFalse);
    await tester.longPress(outlineButton);
    expect(didLongPressButton, isTrue);
  });
1165 1166 1167

  testWidgets('OutlineButton responds to density changes.', (WidgetTester tester) async {
    const Key key = Key('test');
1168
    const Key childKey = Key('test child');
1169 1170

    Future<void> buildTest(VisualDensity visualDensity, {bool useText = false}) async {
1171
      return tester.pumpWidget(
1172 1173 1174 1175 1176 1177 1178 1179
        MaterialApp(
          home: Directionality(
            textDirection: TextDirection.rtl,
            child: Center(
              child: OutlineButton(
                visualDensity: visualDensity,
                key: key,
                onPressed: () {},
1180
                child: useText ? const Text('Text', key: childKey) : Container(key: childKey, width: 100, height: 100, color: const Color(0xffff0000)),
1181 1182 1183 1184 1185 1186 1187
              ),
            ),
          ),
        ),
      );
    }

1188
    await buildTest(VisualDensity.standard);
1189
    final RenderBox box = tester.renderObject(find.byKey(key));
1190
    Rect childRect = tester.getRect(find.byKey(childKey));
1191 1192
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(132, 100)));
1193
    expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
1194 1195 1196

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
    await tester.pumpAndSettle();
1197
    childRect = tester.getRect(find.byKey(childKey));
1198
    expect(box.size, equals(const Size(156, 124)));
1199
    expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
1200 1201 1202

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

1207
    await buildTest(VisualDensity.standard, useText: true);
1208
    await tester.pumpAndSettle();
1209
    childRect = tester.getRect(find.byKey(childKey));
1210
    expect(box.size, equals(const Size(88, 48)));
1211
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
1212 1213 1214

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0), useText: true);
    await tester.pumpAndSettle();
1215
    childRect = tester.getRect(find.byKey(childKey));
1216
    expect(box.size, equals(const Size(112, 60)));
1217
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
1218 1219 1220

    await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0), useText: true);
    await tester.pumpAndSettle();
1221
    childRect = tester.getRect(find.byKey(childKey));
1222
    expect(box.size, equals(const Size(76, 36)));
1223
    expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
1224
  });
1225
}
1226 1227 1228

PhysicalModelLayer _findPhysicalLayer(Element element) {
  expect(element, isNotNull);
1229
  RenderObject? object = element.renderObject;
1230
  while (object != null && object is! RenderRepaintBoundary && object is! RenderView) {
1231
    object = object.parent as RenderObject?;
1232
  }
1233 1234 1235 1236 1237
  assert(object != null);
  expect(object!.debugLayer, isNotNull);
  expect(object.debugLayer!.firstChild, isA<PhysicalModelLayer>());
  final PhysicalModelLayer layer = object.debugLayer!.firstChild! as PhysicalModelLayer;
  final Layer child = layer.firstChild!;
1238
  return child is PhysicalModelLayer ? child : layer;
1239 1240
}

1241
void _checkPhysicalLayer(Element element, Color expectedColor, { Path? clipPath, Rect? clipRect }) {
1242 1243 1244 1245 1246
  final PhysicalModelLayer expectedLayer = _findPhysicalLayer(element);
  expect(expectedLayer.elevation, 0.0);
  expect(expectedLayer.color, expectedColor);
  if (clipPath != null) {
    expect(clipRect, isNotNull);
1247
    expect(expectedLayer.clipPath, coversSameAreaAs(clipPath, areaToCompare: clipRect!.inflate(10.0)));
1248 1249
  }
}
1250 1251 1252 1253 1254

TextStyle _iconStyle(WidgetTester tester, IconData icon) {
  final RichText iconRichText = tester.widget<RichText>(
    find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
  );
1255
  return iconRichText.text.style!;
1256
}