outline_button_test.dart 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/rendering.dart';

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

void main() {
13 14 15
  testWidgets('OutlineButton implements debugFillProperties', (WidgetTester tester) async {
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    OutlineButton(
16
      onPressed: () {},
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
      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 {
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: OutlineButton(
              child: const Text('OutlineButton'),
45
              onPressed: () {},
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
            ),
          ),
        ),
      ),
    );

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

    // Highlighted (pressed).
    final Offset center = tester.getCenter(find.byType(OutlineButton));
    await tester.startGesture(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));
  },
    semanticsEnabled: true,
  );
64

65 66 67 68
  testWidgets('Outline button responds to tap when enabled', (WidgetTester tester) async {
    int pressedCount = 0;

    Widget buildFrame(VoidCallback onPressed) {
69
      return Directionality(
70
        textDirection: TextDirection.ltr,
71 72 73 74
        child: Theme(
          data: ThemeData(),
          child: Center(
            child: OutlineButton(onPressed: onPressed),
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
          ),
        ),
      );
    }

    await tester.pumpWidget(
      buildFrame(() { pressedCount += 1; }),
    );
    expect(tester.widget<OutlineButton>(find.byType(OutlineButton)).enabled, true);
    await tester.tap(find.byType(OutlineButton));
    await tester.pumpAndSettle();
    expect(pressedCount, 1);

    await tester.pumpWidget(
      buildFrame(null),
    );
    final Finder outlineButton = find.byType(OutlineButton);
    expect(tester.widget<OutlineButton>(outlineButton).enabled, false);
    await tester.tap(outlineButton);
    await tester.pumpAndSettle();
    expect(pressedCount, 1);
  });

98 99 100 101 102 103 104 105 106 107 108 109 110
  testWidgets('Outline button doesn\'t crash if disabled during a gesture', (WidgetTester tester) async {
    Widget buildFrame(VoidCallback onPressed) {
      return Directionality(
        textDirection: TextDirection.ltr,
        child: Theme(
          data: ThemeData(),
          child: Center(
            child: OutlineButton(onPressed: onPressed),
          ),
        ),
      );
    }

111
    await tester.pumpWidget(buildFrame(() {}));
112 113 114 115 116
    await tester.press(find.byType(OutlineButton));
    await tester.pumpAndSettle();
    await tester.pumpWidget(buildFrame(null));
    await tester.pumpAndSettle();
  });
117

118
  testWidgets('OutlineButton shape and border component overrides', (WidgetTester tester) async {
119 120 121
    const Color fillColor = Color(0xFF00FF00);
    const Color borderColor = Color(0xFFFF0000);
    const Color highlightedBorderColor = Color(0xFF0000FF);
122
    const Color disabledBorderColor = Color(0xFFFF00FF);
123 124
    const double borderWidth = 4.0;

125
    Widget buildFrame({ VoidCallback onPressed }) {
126
      return Directionality(
127
        textDirection: TextDirection.ltr,
128 129 130
        child: Theme(
          data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
          child: Container(
131
            alignment: Alignment.topLeft,
132
            child: OutlineButton(
133
              shape: const RoundedRectangleBorder(), // default border radius is 0
134
              clipBehavior: Clip.antiAlias,
135
              color: fillColor,
136 137 138 139
              // 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,
140
              highlightedBorderColor: highlightedBorderColor,
141
              disabledBorderColor: disabledBorderColor,
142 143 144 145
              borderSide: const BorderSide(
                width: borderWidth,
                color: borderColor,
              ),
146 147
              onPressed: onPressed,
              child: const Text('button'),
148 149 150
            ),
          ),
        ),
151 152
      );
    }
153

Dan Field's avatar
Dan Field committed
154
    const Rect clipRect = Rect.fromLTRB(0.0, 0.0, 116.0, 36.0);
155
    final Path clipPath = Path()..addRect(clipRect);
156 157 158 159 160 161 162 163 164 165 166

    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(
167
      outlineButton,
168 169
      paints
        ..path(color: disabledBorderColor, strokeWidth: borderWidth));
170
    _checkPhysicalLayer(
171 172 173 174 175
      tester.element(outlineButton),
      const Color(0),
      clipPath: clipPath,
      clipRect: clipRect,
    );
176 177 178

    // Pump a new button with a no-op onPressed callback to make it enabled.
    await tester.pumpWidget(
179
      buildFrame(onPressed: () {}),
180 181 182 183 184
    );

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

185
    // Expect that the button is enabled and painted with the enabled border color.
186
    expect(tester.widget<OutlineButton>(outlineButton).enabled, true);
187 188 189
    expect(
      outlineButton,
      paints
190
        ..path(color: borderColor, strokeWidth: borderWidth));
191
    // initially, the interior of the button is transparent
192
    _checkPhysicalLayer(
193 194 195 196 197
      tester.element(outlineButton),
      fillColor.withAlpha(0x00),
      clipPath: clipPath,
      clipRect: clipRect,
    );
198 199 200 201 202 203 204 205 206 207

    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,
      paints
208
        ..path(color: highlightedBorderColor, strokeWidth: borderWidth));
209
    _checkPhysicalLayer(
210 211 212 213 214
      tester.element(outlineButton),
      fillColor.withAlpha(0xFF),
      clipPath: clipPath,
      clipRect: clipRect,
    );
215 216 217 218 219 220 221

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
    expect(
      outlineButton,
      paints
222
        ..path(color: borderColor, strokeWidth: borderWidth));
223
    _checkPhysicalLayer(
224 225 226 227 228
      tester.element(outlineButton),
      fillColor.withAlpha(0x00),
      clipPath: clipPath,
      clipRect: clipRect,
    );
229 230
  });

231
  testWidgets('OutlineButton has no clip by default', (WidgetTester tester) async {
232
    final GlobalKey buttonKey = GlobalKey();
233
    await tester.pumpWidget(
234
      Directionality(
235
        textDirection: TextDirection.ltr,
236 237 238
        child: Material(
          child: Center(
            child: OutlineButton(
239 240 241
              key: buttonKey,
              onPressed: () {},
              child: const Text('ABC'),
242 243 244 245 246 247 248 249
            ),
          ),
        ),
      ),
    );

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

254
  testWidgets('OutlineButton contributes semantics', (WidgetTester tester) async {
255
    final SemanticsTester semantics = SemanticsTester(tester);
256
    await tester.pumpWidget(
257
      Directionality(
258
        textDirection: TextDirection.ltr,
259 260 261
        child: Material(
          child: Center(
            child: OutlineButton(
262
              onPressed: () {},
263
              child: const Text('ABC'),
264 265 266 267 268 269 270
            ),
          ),
        ),
      ),
    );

    expect(semantics, hasSemantics(
271
      TestSemantics.root(
272
        children: <TestSemantics>[
273
          TestSemantics.rootChild(
274 275 276 277
            actions: <SemanticsAction>[
              SemanticsAction.tap,
            ],
            label: 'ABC',
Dan Field's avatar
Dan Field committed
278
            rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
279
            transform: Matrix4.translationValues(356.0, 276.0, 0.0),
280 281 282 283 284
            flags: <SemanticsFlag>[
              SemanticsFlag.isButton,
              SemanticsFlag.hasEnabledState,
              SemanticsFlag.isEnabled,
            ],
285
          ),
286 287 288 289 290 291 292 293 294 295
        ],
      ),
      ignoreId: true,
    ));

    semantics.dispose();
  });

  testWidgets('OutlineButton scales textScaleFactor', (WidgetTester tester) async {
    await tester.pumpWidget(
296
      Directionality(
297
        textDirection: TextDirection.ltr,
298 299
        child: Material(
          child: MediaQuery(
300
            data: const MediaQueryData(textScaleFactor: 1.0),
301 302
            child: Center(
              child: OutlineButton(
303
                onPressed: () {},
304 305 306 307 308 309 310 311
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

312
    expect(tester.getSize(find.byType(OutlineButton)), equals(const Size(88.0, 48.0)));
313 314 315 316
    expect(tester.getSize(find.byType(Text)), equals(const Size(42.0, 14.0)));

    // textScaleFactor expands text, but not button.
    await tester.pumpWidget(
317
      Directionality(
318
        textDirection: TextDirection.ltr,
319 320
        child: Material(
          child: MediaQuery(
321
            data: const MediaQueryData(textScaleFactor: 1.3),
322 323
            child: Center(
              child: FlatButton(
324
                onPressed: () {},
325 326 327 328 329 330 331 332
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

333
    expect(tester.getSize(find.byType(FlatButton)), equals(const Size(88.0, 48.0)));
334
    // Scaled text rendering is different on Linux and Mac by one pixel.
335
    // TODO(gspencergoog): Figure out why this is, and fix it. https://github.com/flutter/flutter/issues/12357
336 337 338 339 340
    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(
341
      Directionality(
342
        textDirection: TextDirection.ltr,
343 344
        child: Material(
          child: MediaQuery(
345
            data: const MediaQueryData(textScaleFactor: 3.0),
346 347
            child: Center(
              child: FlatButton(
348
                onPressed: () {},
349 350 351 352 353 354 355 356 357
                child: const Text('ABC'),
              ),
            ),
          ),
        ),
      ),
    );

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

365 366 367 368 369 370 371
  testWidgets('OutlineButton pressed fillColor default', (WidgetTester tester) async {
    Widget buildFrame(ThemeData theme) {
      return MaterialApp(
        theme: theme,
        home: Scaffold(
          body: Center(
            child: OutlineButton(
372
              onPressed: () {},
373 374 375 376
              // 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,
377 378 379 380 381 382 383 384 385
              child: const Text('Hello'),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame(ThemeData.dark()));
    final Finder button = find.byType(OutlineButton);
386
    final Element buttonElement = tester.element(button);
387 388 389 390 391 392 393
    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.
    Color fillColor = Colors.grey[850];

    // Initially the interior of the button is transparent.
394
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
395 396 397 398 399

    // 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.
400
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0xFF));
401 402 403 404

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
405
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
406 407 408 409 410 411 412 413 414

    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.
    fillColor = Colors.grey[50];

    // Initially the interior of the button is transparent.
415
    // expect(button, paints..path(color: fillColor.withAlpha(0x00)));
416 417 418 419 420

    // 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.
421
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0xFF));
422 423 424 425

    // Tap gesture completes, button returns to its initial configuration.
    await gesture.up();
    await tester.pumpAndSettle();
426
    _checkPhysicalLayer(buttonElement, fillColor.withAlpha(0x00));
427
  });
428
}
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

PhysicalModelLayer _findPhysicalLayer(Element element) {
  expect(element, isNotNull);
  RenderObject object = element.renderObject;
  while (object != null && object is! RenderRepaintBoundary && object is! RenderView) {
    object = object.parent;
  }
  expect(object.debugLayer, isNotNull);
  expect(object.debugLayer.firstChild, isInstanceOf<PhysicalModelLayer>());
  final PhysicalModelLayer layer = object.debugLayer.firstChild;
  return layer.firstChild is PhysicalModelLayer ? layer.firstChild : layer;
}

void _checkPhysicalLayer(Element element, Color expectedColor, { Path clipPath, Rect clipRect }) {
  final PhysicalModelLayer expectedLayer = _findPhysicalLayer(element);
  expect(expectedLayer.elevation, 0.0);
  expect(expectedLayer.color, expectedColor);
  if (clipPath != null) {
    expect(clipRect, isNotNull);
    expect(expectedLayer.clipPath, coversSameAreaAs(clipPath, areaToCompare: clipRect.inflate(10.0)));
  }
}