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

import 'dart:ui';

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

13
import '../rendering/mock_canvas.dart';
14 15 16
import '../widgets/semantics_tester.dart';

void main() {
17 18 19 20
  setUp(() {
    debugResetSemanticsIdCounter();
  });

21
  testWidgets('Checkbox size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
22
    await tester.pumpWidget(
23 24 25
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded),
        child: Directionality(
26
          textDirection: TextDirection.ltr,
27 28 29
          child: Material(
            child: Center(
              child: Checkbox(
30
                value: true,
31
                onChanged: (bool newValue) { },
32 33 34 35 36 37 38 39 40 41
              ),
            ),
          ),
        ),
      ),
    );

    expect(tester.getSize(find.byType(Checkbox)), const Size(48.0, 48.0));

    await tester.pumpWidget(
42 43 44
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
        child: Directionality(
45
          textDirection: TextDirection.ltr,
46 47 48
          child: Material(
            child: Center(
              child: Checkbox(
49
                value: true,
50
                onChanged: (bool newValue) { },
51 52
              ),
            ),
53 54 55 56 57 58 59 60
          ),
        ),
      ),
    );

    expect(tester.getSize(find.byType(Checkbox)), const Size(40.0, 40.0));
  });

61
  testWidgets('CheckBox semantics', (WidgetTester tester) async {
62
    final SemanticsHandle handle = tester.ensureSemantics();
63

64 65
    await tester.pumpWidget(Material(
      child: Checkbox(
66 67 68 69 70
        value: false,
        onChanged: (bool b) { },
      ),
    ));

71
    expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
72 73 74 75
      hasCheckedState: true,
      hasEnabledState: true,
      isEnabled: true,
      hasTapAction: true,
76
      isFocusable: true,
77
    ));
78

79 80
    await tester.pumpWidget(Material(
      child: Checkbox(
81 82 83 84 85
        value: true,
        onChanged: (bool b) { },
      ),
    ));

86
    expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
87 88 89 90 91
      hasCheckedState: true,
      hasEnabledState: true,
      isChecked: true,
      isEnabled: true,
      hasTapAction: true,
92
      isFocusable: true,
93
    ));
94 95

    await tester.pumpWidget(const Material(
96
      child: Checkbox(
97 98 99 100 101
        value: false,
        onChanged: null,
      ),
    ));

102
    expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
103 104 105
      hasCheckedState: true,
      hasEnabledState: true,
    ));
106 107

    await tester.pumpWidget(const Material(
108
      child: Checkbox(
109 110 111 112 113
        value: true,
        onChanged: null,
      ),
    ));

114
    expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
115 116 117 118 119
      hasCheckedState: true,
      hasEnabledState: true,
      isChecked: true,
    ));
    handle.dispose();
120
  });
121

122
  testWidgets('Can wrap CheckBox with Semantics', (WidgetTester tester) async {
123
    final SemanticsHandle handle = tester.ensureSemantics();
124

125 126
    await tester.pumpWidget(Material(
      child: Semantics(
127 128
        label: 'foo',
        textDirection: TextDirection.ltr,
129
        child: Checkbox(
130 131 132 133 134 135
          value: false,
          onChanged: (bool b) { },
        ),
      ),
    ));

136
    expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
137 138 139 140 141 142
      label: 'foo',
      textDirection: TextDirection.ltr,
      hasCheckedState: true,
      hasEnabledState: true,
      isEnabled: true,
      hasTapAction: true,
143
      isFocusable: true,
144 145
    ));
    handle.dispose();
146 147
  });

148 149 150 151
  testWidgets('CheckBox tristate: true', (WidgetTester tester) async {
    bool checkBoxValue;

    await tester.pumpWidget(
152 153
      Material(
        child: StatefulBuilder(
154
          builder: (BuildContext context, StateSetter setState) {
155
            return Checkbox(
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
              tristate: true,
              value: checkBoxValue,
              onChanged: (bool value) {
                setState(() {
                  checkBoxValue = value;
                });
              },
            );
          },
        ),
      ),
    );

    expect(tester.widget<Checkbox>(find.byType(Checkbox)).value, null);

    await tester.tap(find.byType(Checkbox));
    await tester.pumpAndSettle();
    expect(checkBoxValue, false);

    await tester.tap(find.byType(Checkbox));
    await tester.pumpAndSettle();
    expect(checkBoxValue, true);

    await tester.tap(find.byType(Checkbox));
    await tester.pumpAndSettle();
    expect(checkBoxValue, null);

    checkBoxValue = true;
    await tester.pumpAndSettle();
    expect(checkBoxValue, true);

    checkBoxValue = null;
    await tester.pumpAndSettle();
    expect(checkBoxValue, null);
  });
191

192
  testWidgets('has semantics for tristate', (WidgetTester tester) async {
193
    final SemanticsTester semantics = SemanticsTester(tester);
194
    await tester.pumpWidget(
195 196
      Material(
        child: Checkbox(
197 198
          tristate: true,
          value: null,
199
          onChanged: (bool newValue) { },
200 201 202 203 204 205 206 207
        ),
      ),
    );

    expect(semantics.nodesWith(
      flags: <SemanticsFlag>[
        SemanticsFlag.hasCheckedState,
        SemanticsFlag.hasEnabledState,
208
        SemanticsFlag.isEnabled,
209
        SemanticsFlag.isFocusable,
210 211 212 213 214
      ],
      actions: <SemanticsAction>[SemanticsAction.tap],
    ), hasLength(1));

    await tester.pumpWidget(
215 216
      Material(
        child: Checkbox(
217 218
          tristate: true,
          value: true,
219
          onChanged: (bool newValue) { },
220 221 222 223 224 225 226 227 228 229
        ),
      ),
    );

    expect(semantics.nodesWith(
      flags: <SemanticsFlag>[
        SemanticsFlag.hasCheckedState,
        SemanticsFlag.hasEnabledState,
        SemanticsFlag.isEnabled,
        SemanticsFlag.isChecked,
230
        SemanticsFlag.isFocusable,
231 232 233 234 235
      ],
      actions: <SemanticsAction>[SemanticsAction.tap],
    ), hasLength(1));

    await tester.pumpWidget(
236 237
      Material(
        child: Checkbox(
238 239
          tristate: true,
          value: false,
240
          onChanged: (bool newValue) { },
241 242 243 244 245 246 247 248 249
        ),
      ),
    );

    expect(semantics.nodesWith(
      flags: <SemanticsFlag>[
        SemanticsFlag.hasCheckedState,
        SemanticsFlag.hasEnabledState,
        SemanticsFlag.isEnabled,
250
        SemanticsFlag.isFocusable,
251 252 253 254 255 256 257
      ],
      actions: <SemanticsAction>[SemanticsAction.tap],
    ), hasLength(1));

    semantics.dispose();
  });

258 259 260
  testWidgets('has semantic events', (WidgetTester tester) async {
    dynamic semanticEvent;
    bool checkboxValue = false;
261
    SystemChannels.accessibility.setMockMessageHandler((dynamic message) async {
262 263
      semanticEvent = message;
    });
264
    final SemanticsTester semanticsTester = SemanticsTester(tester);
265 266

    await tester.pumpWidget(
267 268
      Material(
        child: StatefulBuilder(
269
          builder: (BuildContext context, StateSetter setState) {
270
            return Checkbox(
271 272 273 274 275 276 277 278 279 280 281 282 283
              value: checkboxValue,
              onChanged: (bool value) {
                setState(() {
                  checkboxValue = value;
                });
              },
            );
          },
        ),
      ),
    );

    await tester.tap(find.byType(Checkbox));
284
    final RenderObject object = tester.firstRenderObject(find.byType(Focus));
285 286 287 288 289 290 291 292 293 294 295 296

    expect(checkboxValue, true);
    expect(semanticEvent, <String, dynamic>{
      'type': 'tap',
      'nodeId': object.debugSemantics.id,
      'data': <String, dynamic>{},
    });
    expect(object.debugSemantics.getSemanticsData().hasAction(SemanticsAction.tap), true);

    SystemChannels.accessibility.setMockMessageHandler(null);
    semanticsTester.dispose();
  });
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

  testWidgets('CheckBox tristate rendering, programmatic transitions', (WidgetTester tester) async {
    Widget buildFrame(bool checkboxValue) {
      return Material(
        child: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return Checkbox(
              tristate: true,
              value: checkboxValue,
              onChanged: (bool value) { },
            );
          },
        ),
      );
    }

    RenderToggleable getCheckboxRenderer() {
314 315 316
      return tester.renderObject<RenderToggleable>(find.byWidgetPredicate((Widget widget) {
        return widget.runtimeType.toString() == '_CheckboxRenderObjectWidget';
      }));
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    }

    await tester.pumpWidget(buildFrame(false));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), isNot(paints..path())); // checkmark is rendered as a path
    expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
    expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox

    await tester.pumpWidget(buildFrame(true));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..path()); // checkmark is rendered as a path

    await tester.pumpWidget(buildFrame(false));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), isNot(paints..path())); // checkmark is rendered as a path
    expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
    expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox

    await tester.pumpWidget(buildFrame(null));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")

    await tester.pumpWidget(buildFrame(true));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..path()); // checkmark is rendered as a path

    await tester.pumpWidget(buildFrame(null));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")
  });

348
  testWidgets('CheckBox color rendering', (WidgetTester tester) async {
349
    Widget buildFrame({Color activeColor, Color checkColor, ThemeData themeData}) {
350
      return Material(
351 352 353 354 355 356 357 358 359 360 361 362
        child: Theme(
          data: themeData ?? ThemeData(),
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Checkbox(
                value: true,
                activeColor: activeColor,
                checkColor: checkColor,
                onChanged: (bool value) { },
              );
            },
          ),
363 364 365 366 367
        ),
      );
    }

    RenderToggleable getCheckboxRenderer() {
368 369 370
      return tester.renderObject<RenderToggleable>(find.byWidgetPredicate((Widget widget) {
        return widget.runtimeType.toString() == '_CheckboxRenderObjectWidget';
      }));
371 372
    }

373
    await tester.pumpWidget(buildFrame(checkColor: const Color(0xFFFFFFFF)));
374 375 376
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..path(color: const Color(0xFFFFFFFF))); // paints's color is 0xFFFFFFFF (default color)

377
    await tester.pumpWidget(buildFrame(checkColor: const Color(0xFF000000)));
378 379
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..path(color: const Color(0xFF000000))); // paints's color is 0xFF000000 (params)
380 381 382 383 384 385 386 387

    await tester.pumpWidget(buildFrame(themeData: ThemeData(toggleableActiveColor: const Color(0xFF00FF00))));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..rrect(color: const Color(0xFF00FF00))); // paints's color is 0xFF00FF00 (theme)

    await tester.pumpWidget(buildFrame(activeColor: const Color(0xFF000000)));
    await tester.pumpAndSettle();
    expect(getCheckboxRenderer(), paints..rrect(color: const Color(0xFF000000))); // paints's color is 0xFF000000 (params)
388 389
  });

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  testWidgets('Checkbox is focusable and has correct focus color', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    bool value = true;
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Checkbox(
                value: value,
                onChanged: enabled ? (bool newValue) {
                  setState(() {
                    value = newValue;
                  });
                } : null,
                focusColor: Colors.orange[500],
                autofocus: true,
                focusNode: focusNode,
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());

    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..circle(color: Colors.orange[500])
        ..rrect(
            color: const Color(0xff1e88e5),
            rrect: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)))
        ..path(color: Colors.white),
    );

    // Check the false value.
    value = false;
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..circle(color: Colors.orange[500])
        ..drrect(
            color: const Color(0x8a000000),
            outer: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)),
        inner: RRect.fromLTRBR(393.0,
            293.0, 407.0, 307.0, const Radius.circular(-1.0))),
    );

    // Check what happens when disabled.
    value = false;
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isFalse);
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..drrect(
            color: const Color(0x61000000),
            outer: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)),
            inner: RRect.fromLTRBR(393.0,
                293.0, 407.0, 307.0, const Radius.circular(-1.0))),
    );
  });

  testWidgets('Checkbox can be hovered and has correct hover color', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    bool value = true;
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Checkbox(
                value: value,
                onChanged: enabled ? (bool newValue) {
                  setState(() {
                    value = newValue;
                  });
                } : null,
                hoverColor: Colors.orange[500],
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..rrect(
            color: const Color(0xff1e88e5),
            rrect: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)))
        ..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
    );

    // Start hovering
    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
    addTearDown(gesture.removePointer);
    await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));

    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..rrect(
            color: const Color(0xff1e88e5),
            rrect: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)))
        ..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
    );

    // Check what happens when disabled.
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Checkbox))),
      paints
        ..rrect(
            color: const Color(0x61000000),
            rrect: RRect.fromLTRBR(
                391.0, 291.0, 409.0, 309.0, const Radius.circular(1.0)))
        ..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
    );
  });

  testWidgets('Checkbox can be toggled by keyboard shortcuts', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    bool value = true;
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Checkbox(
                value: value,
                onChanged: enabled ? (bool newValue) {
                  setState(() {
                    value = newValue;
                  });
                } : null,
                focusColor: Colors.orange[500],
                autofocus: true,
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    await tester.sendKeyEvent(LogicalKeyboardKey.enter);
    await tester.pumpAndSettle();
    // On web, switches don't respond to the enter key.
    expect(value, kIsWeb ? isTrue : isFalse);
    await tester.sendKeyEvent(LogicalKeyboardKey.enter);
    await tester.pumpAndSettle();
    expect(value, isTrue);
    await tester.sendKeyEvent(LogicalKeyboardKey.space);
    await tester.pumpAndSettle();
    expect(value, isFalse);
    await tester.sendKeyEvent(LogicalKeyboardKey.space);
    await tester.pumpAndSettle();
    expect(value, isTrue);
  });
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

  testWidgets('Checkbox responds to density changes.', (WidgetTester tester) async {
    const Key key = Key('test');
    Future<void> buildTest(VisualDensity visualDensity) async {
      return await tester.pumpWidget(
        MaterialApp(
          home: Material(
            child: Center(
              child: Checkbox(
                visualDensity: visualDensity,
                key: key,
                onChanged: (bool value) {},
                value: true,
              ),
            ),
          ),
        ),
      );
    }

    await buildTest(const VisualDensity());
    final RenderBox box = tester.renderObject(find.byKey(key));
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(48, 48)));

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(60, 60)));

    await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(36, 36)));

    await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0));
    await tester.pumpAndSettle();
    expect(box.size, equals(const Size(60, 36)));
  });
605
}