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

5 6
import 'dart:ui';

7
import 'package:flutter/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
import '../widgets/semantics_tester.dart';

16 17
void main() {
  testWidgets('Radio control test', (WidgetTester tester) async {
18
    final Key key = UniqueKey();
19
    final List<int?> log = <int?>[];
20

21 22 23
    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
24 25 26
          key: key,
          value: 1,
          groupValue: 2,
27
          onChanged: log.add,
28 29 30 31 32 33 34 35 36
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

    expect(log, equals(<int>[1]));
    log.clear();

37 38 39
    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
40 41 42
          key: key,
          value: 1,
          groupValue: 1,
43
          onChanged: log.add,
44 45 46 47 48 49 50 51 52
          activeColor: Colors.green[500],
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

    expect(log, isEmpty);

53 54 55
    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
56 57 58 59 60 61 62 63 64 65 66 67
          key: key,
          value: 1,
          groupValue: 2,
          onChanged: null,
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

    expect(log, isEmpty);
  });
68

69 70
  testWidgets('Radio can be toggled when toggleable is set', (WidgetTester tester) async {
    final Key key = UniqueKey();
71
    final List<int?> log = <int?>[];
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
          key: key,
          value: 1,
          groupValue: 2,
          onChanged: log.add,
          toggleable: true,
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

    expect(log, equals(<int>[1]));
    log.clear();

    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
          key: key,
          value: 1,
          groupValue: 1,
          onChanged: log.add,
          toggleable: true,
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

104
    expect(log, equals(<int?>[null]));
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    log.clear();

    await tester.pumpWidget(Material(
      child: Center(
        child: Radio<int>(
          key: key,
          value: 1,
          groupValue: null,
          onChanged: log.add,
          toggleable: true,
        ),
      ),
    ));

    await tester.tap(find.byKey(key));

    expect(log, equals(<int>[1]));
  });

124
  testWidgets('Radio size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
125
    final Key key1 = UniqueKey();
126
    await tester.pumpWidget(
127 128 129
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded),
        child: Directionality(
130
          textDirection: TextDirection.ltr,
131 132 133
          child: Material(
            child: Center(
              child: Radio<bool>(
134 135 136
                key: key1,
                groupValue: true,
                value: true,
137
                onChanged: (bool? newValue) { },
138 139 140 141 142 143 144 145
              ),
            ),
          ),
        ),
      ),
    );

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

147
    final Key key2 = UniqueKey();
148
    await tester.pumpWidget(
149 150 151
      Theme(
        data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
        child: Directionality(
152
          textDirection: TextDirection.ltr,
153 154 155
          child: Material(
            child: Center(
              child: Radio<bool>(
156 157 158
                key: key2,
                groupValue: true,
                value: true,
159
                onChanged: (bool? newValue) { },
160 161
              ),
            ),
162 163 164 165 166
          ),
        ),
      ),
    );

167
    expect(tester.getSize(find.byKey(key2)), const Size(40.0, 40.0));
168 169 170
  });


171
  testWidgets('Radio semantics', (WidgetTester tester) async {
172
    final SemanticsTester semantics = SemanticsTester(tester);
173

174 175
    await tester.pumpWidget(Material(
      child: Radio<int>(
176 177
        value: 1,
        groupValue: 2,
178
        onChanged: (int? i) { },
179 180 181
      ),
    ));

182
    expect(semantics, hasSemantics(TestSemantics.root(
183
      children: <TestSemantics>[
184
        TestSemantics.rootChild(
185 186 187 188 189 190
          id: 1,
          flags: <SemanticsFlag>[
            SemanticsFlag.isInMutuallyExclusiveGroup,
            SemanticsFlag.hasCheckedState,
            SemanticsFlag.hasEnabledState,
            SemanticsFlag.isEnabled,
191
            SemanticsFlag.isFocusable,
192 193 194 195 196 197 198 199
          ],
          actions: <SemanticsAction>[
            SemanticsAction.tap,
          ],
        ),
      ],
    ), ignoreRect: true, ignoreTransform: true));

200 201
    await tester.pumpWidget(Material(
      child: Radio<int>(
202 203
        value: 2,
        groupValue: 2,
204
        onChanged: (int? i) { },
205 206 207
      ),
    ));

208
    expect(semantics, hasSemantics(TestSemantics.root(
209
      children: <TestSemantics>[
210
        TestSemantics.rootChild(
211 212 213 214 215 216 217
          id: 1,
          flags: <SemanticsFlag>[
            SemanticsFlag.isInMutuallyExclusiveGroup,
            SemanticsFlag.hasCheckedState,
            SemanticsFlag.isChecked,
            SemanticsFlag.hasEnabledState,
            SemanticsFlag.isEnabled,
218
            SemanticsFlag.isFocusable,
219 220 221 222 223 224 225 226 227
          ],
          actions: <SemanticsAction>[
            SemanticsAction.tap,
          ],
        ),
      ],
    ), ignoreRect: true, ignoreTransform: true));

    await tester.pumpWidget(const Material(
228
      child: Radio<int>(
229 230 231 232 233 234
        value: 1,
        groupValue: 2,
        onChanged: null,
      ),
    ));

235
    expect(semantics, hasSemantics(TestSemantics.root(
236
      children: <TestSemantics>[
237
        TestSemantics.rootChild(
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
          id: 1,
          flags: <SemanticsFlag>[
            SemanticsFlag.hasCheckedState,
            SemanticsFlag.hasEnabledState,
            SemanticsFlag.isInMutuallyExclusiveGroup,
            SemanticsFlag.isFocusable,  // This flag is delayed by 1 frame.
          ],
        ),
      ],
    ), ignoreRect: true, ignoreTransform: true));

    await tester.pump();

    // Now the isFocusable should be gone.
    expect(semantics, hasSemantics(TestSemantics.root(
      children: <TestSemantics>[
        TestSemantics.rootChild(
          id: 1,
256 257 258
          flags: <SemanticsFlag>[
            SemanticsFlag.hasCheckedState,
            SemanticsFlag.hasEnabledState,
259
            SemanticsFlag.isInMutuallyExclusiveGroup,
260 261 262 263 264 265
          ],
        ),
      ],
    ), ignoreRect: true, ignoreTransform: true));

    await tester.pumpWidget(const Material(
266
      child: Radio<int>(
267 268 269 270 271 272
        value: 2,
        groupValue: 2,
        onChanged: null,
      ),
    ));

273
    expect(semantics, hasSemantics(TestSemantics.root(
274
      children: <TestSemantics>[
275
        TestSemantics.rootChild(
276
          id: 1,
277 278 279 280
          flags: <SemanticsFlag>[
            SemanticsFlag.hasCheckedState,
            SemanticsFlag.isChecked,
            SemanticsFlag.hasEnabledState,
281
            SemanticsFlag.isInMutuallyExclusiveGroup,
282 283 284 285 286 287 288
          ],
        ),
      ],
    ), ignoreRect: true, ignoreTransform: true));

    semantics.dispose();
  });
289 290

  testWidgets('has semantic events', (WidgetTester tester) async {
291 292
    final SemanticsTester semantics = SemanticsTester(tester);
    final Key key = UniqueKey();
293
    dynamic semanticEvent;
294
    int? radioValue = 2;
295
    SystemChannels.accessibility.setMockMessageHandler((dynamic message) async {
296 297 298
      semanticEvent = message;
    });

299 300
    await tester.pumpWidget(Material(
      child: Radio<int>(
301 302 303
        key: key,
        value: 1,
        groupValue: radioValue,
304
        onChanged: (int? i) {
305 306 307 308 309 310
          radioValue = i;
        },
      ),
    ));

    await tester.tap(find.byKey(key));
311
    final RenderObject object = tester.firstRenderObject(find.byType(Focus));
312 313 314 315

    expect(radioValue, 1);
    expect(semanticEvent, <String, dynamic>{
      'type': 'tap',
316
      'nodeId': object.debugSemantics!.id,
317 318
      'data': <String, dynamic>{},
    });
319
    expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true);
320 321 322 323

    semantics.dispose();
    SystemChannels.accessibility.setMockMessageHandler(null);
  });
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

  testWidgets('Radio ink ripple is displayed correctly', (WidgetTester tester) async {
    final Key painterKey = UniqueKey();
    const Key radioKey = Key('radio');

    await tester.pumpWidget(MaterialApp(
      theme: ThemeData(),
      home: Scaffold(
        body: RepaintBoundary(
          key: painterKey,
          child: Center(
            child: Container(
              width: 100,
              height: 100,
              color: Colors.white,
              child: Radio<int>(
                key: radioKey,
                value: 1,
                groupValue: 1,
343
                onChanged: (int? value) { },
344
              ),
345
            ),
346 347 348 349 350 351 352 353 354
          ),
        ),
      ),
    ));

    await tester.press(find.byKey(radioKey));
    await tester.pumpAndSettle();
    await expectLater(
      find.byKey(painterKey),
355
      matchesGoldenFile('radio.ink_ripple.png'),
356
    );
357
  });
358 359 360 361

  testWidgets('Radio is focusable and has correct focus color', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode(debugLabel: 'Radio');
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
362
    int? groupValue = 0;
363 364 365 366 367 368 369 370 371 372 373 374 375
    const Key radioKey = Key('radio');
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Container(
                width: 100,
                height: 100,
                color: Colors.white,
                child: Radio<int>(
                  key: radioKey,
                  value: 0,
376
                  onChanged: enabled ? (int? newValue) {
377 378 379 380 381 382 383 384 385 386 387 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
                    setState(() {
                      groupValue = newValue;
                    });
                  } : null,
                  focusColor: Colors.orange[500],
                  autofocus: true,
                  focusNode: focusNode,
                  groupValue: groupValue,
                ),
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());

    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(
      Material.of(tester.element(find.byKey(radioKey))),
      paints
        ..rect(
            color: const Color(0xffffffff),
            rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
        ..circle(color: Colors.orange[500])
        ..circle(color: const Color(0xff1e88e5))
        ..circle(color: const Color(0xff1e88e5)),
    );

    // Check when the radio isn't selected.
    groupValue = 1;
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(
      Material.of(tester.element(find.byKey(radioKey))),
      paints
        ..rect(
            color: const Color(0xffffffff),
            rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
        ..circle(color: Colors.orange[500])
        ..circle(color: const Color(0x8a000000), style: PaintingStyle.stroke, strokeWidth: 2.0)
    );

    // Check when the radio is selected, but disabled.
    groupValue = 0;
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isFalse);
    expect(
      Material.of(tester.element(find.byKey(radioKey))),
      paints
        ..rect(
            color: const Color(0xffffffff),
            rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
        ..circle(color: const Color(0x61000000))
        ..circle(color: const Color(0x61000000)),
    );
  });

438
  testWidgets('Radio can be hovered and has correct hover color', (WidgetTester tester) async {
439
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
440
    int? groupValue = 0;
441 442 443 444 445 446 447 448 449 450 451 452 453
    const Key radioKey = Key('radio');
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Container(
                width: 100,
                height: 100,
                color: Colors.white,
                child: Radio<int>(
                  key: radioKey,
                  value: 0,
454
                  onChanged: enabled ? (int? newValue) {
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                    setState(() {
                      groupValue = newValue;
                    });
                  } : null,
                  hoverColor: Colors.orange[500],
                  groupValue: groupValue,
                ),
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());

470
    await tester.pump();
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byKey(radioKey))),
      paints
        ..rect(
            color: const Color(0xffffffff),
            rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
        ..circle(color: const Color(0xff1e88e5))
        ..circle(color: const Color(0xff1e88e5)),
    );

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

    // Check when the radio isn't selected.
    groupValue = 1;
    await tester.pumpWidget(buildApp());
490
    await tester.pump();
491 492 493 494 495 496 497 498
    await tester.pumpAndSettle();
    expect(
        Material.of(tester.element(find.byKey(radioKey))),
        paints
          ..rect(
              color: const Color(0xffffffff),
              rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
          ..circle(color: Colors.orange[500])
499
          ..circle(color: const Color(0x8a000000), style: PaintingStyle.stroke, strokeWidth: 2.0),
500 501 502 503 504
    );

    // Check when the radio is selected, but disabled.
    groupValue = 0;
    await tester.pumpWidget(buildApp(enabled: false));
505
    await tester.pump();
506 507 508 509 510 511 512 513 514 515 516 517
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byKey(radioKey))),
      paints
        ..rect(
            color: const Color(0xffffffff),
            rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0))
        ..circle(color: const Color(0x61000000))
        ..circle(color: const Color(0x61000000)),
    );
  });

518
  testWidgets('Radio can be controlled by keyboard shortcuts', (WidgetTester tester) async {
519
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
520
    int? groupValue = 1;
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    const Key radioKey0 = Key('radio0');
    const Key radioKey1 = Key('radio1');
    const Key radioKey2 = Key('radio2');
    final FocusNode focusNode2 = FocusNode(debugLabel: 'radio2');
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Container(
                width: 200,
                height: 100,
                color: Colors.white,
                child: Row(
                  children: <Widget>[
                    Radio<int>(
                      key: radioKey0,
                      value: 0,
539
                      onChanged: enabled ? (int? newValue) {
540 541 542 543 544 545 546 547 548 549 550
                        setState(() {
                          groupValue = newValue;
                        });
                      } : null,
                      hoverColor: Colors.orange[500],
                      groupValue: groupValue,
                      autofocus: true,
                    ),
                    Radio<int>(
                      key: radioKey1,
                      value: 1,
551
                      onChanged: enabled ? (int? newValue) {
552 553 554 555 556 557 558 559 560 561
                        setState(() {
                          groupValue = newValue;
                        });
                      } : null,
                      hoverColor: Colors.orange[500],
                      groupValue: groupValue,
                    ),
                    Radio<int>(
                      key: radioKey2,
                      value: 2,
562
                      onChanged: enabled ? (int? newValue) {
563 564 565 566 567 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
                        setState(() {
                          groupValue = newValue;
                        });
                      } : null,
                      hoverColor: Colors.orange[500],
                      groupValue: groupValue,
                      focusNode: focusNode2,
                    ),
                  ],
                ),
              );
            }),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.enter);
    await tester.pumpAndSettle();
    // On web, radios don't respond to the enter key.
    expect(groupValue, kIsWeb ? equals(1) : equals(0));

    focusNode2.requestFocus();
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.space);
    await tester.pumpAndSettle();
    expect(groupValue, equals(2));
  });

596 597 598 599 600 601 602 603 604 605
  testWidgets('Radio 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: Radio<int>(
                visualDensity: visualDensity,
                key: key,
606
                onChanged: (int? value) {},
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
                value: 0,
                groupValue: 0,
              ),
            ),
          ),
        ),
      );
    }

    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)));
  });
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

  testWidgets('Radio changes mouse cursor when hovered', (WidgetTester tester) async {
    const Key key = ValueKey<int>(1);
    // Test Radio() constructor
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Align(
            alignment: Alignment.topLeft,
            child: Material(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Radio<int>(
                  key: key,
                  mouseCursor: SystemMouseCursors.text,
                  value: 1,
649
                  onChanged: (int? v) {},
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                  groupValue: 2,
                ),
              ),
            ),
          ),
        ),
      ),
    );

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: tester.getCenter(find.byKey(key)));
    addTearDown(gesture.removePointer);

    await tester.pump();

665
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
666 667 668 669 670 671 672 673 674 675 676 677 678


    // Test default cursor
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Align(
            alignment: Alignment.topLeft,
            child: Material(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Radio<int>(
                  value: 1,
679
                  onChanged: (int? v) {},
680 681 682 683 684 685 686 687 688
                  groupValue: 2,
                ),
              ),
            ),
          ),
        ),
      ),
    );

689
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711

    // Test default cursor when disabled
    await tester.pumpWidget(
      const MaterialApp(
        home: Scaffold(
          body: Align(
            alignment: Alignment.topLeft,
            child: Material(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Radio<int>(
                  value: 1,
                  onChanged: null,
                  groupValue: 2,
                ),
              ),
            ),
          ),
        ),
      ),
    );

712
    expect(RendererBinding.instance!.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
713
  });
714
}