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

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

12
import '../rendering/rendering_tester.dart';
13

14 15 16 17 18 19
class SpyFixedExtentScrollController extends FixedExtentScrollController {
  /// Override for test visibility only.
  @override
  bool get hasListeners => super.hasListeners;
}

20
void main() {
21 22 23 24 25 26 27 28 29 30 31 32
  testWidgets('Picker respects theme styling', (WidgetTester tester) async {
    await tester.pumpWidget(
      CupertinoApp(
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              itemExtent: 50.0,
              onSelectedItemChanged: (_) { },
              children: List<Widget>.generate(3, (int index) {
33
                return SizedBox(
34 35 36 37 38 39 40 41 42 43 44 45 46
                  height: 50.0,
                  width: 300.0,
                  child: Text(index.toString()),
                );
              }),
            ),
          ),
        ),
      ),
    );

    final RenderParagraph paragraph = tester.renderObject(find.text('1'));

47 48
    expect(paragraph.text.style!.color, isSameColorAs(CupertinoColors.black));
    expect(paragraph.text.style!.copyWith(color: CupertinoColors.black), const TextStyle(
49 50
      inherit: false,
      fontFamily: '.SF Pro Display',
51
      fontSize: 21.0,
52
      fontWeight: FontWeight.w400,
53
      letterSpacing: -0.6,
54 55 56 57
      color: CupertinoColors.black,
    ));
  });

58
  group('layout', () {
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    // Regression test for https://github.com/flutter/flutter/issues/22999
    testWidgets('CupertinoPicker.builder test', (WidgetTester tester) async {
      Widget buildFrame(int childCount) {
        return Directionality(
          textDirection: TextDirection.ltr,
          child: CupertinoPicker.builder(
            itemExtent: 50.0,
            onSelectedItemChanged: (_) { },
            itemBuilder: (BuildContext context, int index) {
              return Text('$index');
            },
            childCount: childCount,
          ),
        );
      }

      await tester.pumpWidget(buildFrame(1));
      expect(tester.renderObject(find.text('0')).attached, true);

      await tester.pumpWidget(buildFrame(2));
      expect(tester.renderObject(find.text('0')).attached, true);
      expect(tester.renderObject(find.text('1')).attached, true);
    });

83
    testWidgets('selected item is in the middle', (WidgetTester tester) async {
84
      final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 1);
85 86

      await tester.pumpWidget(
87
        Directionality(
88
          textDirection: TextDirection.ltr,
89
          child: Align(
90
            alignment: Alignment.topLeft,
91
            child: SizedBox(
92 93
              height: 300.0,
              width: 300.0,
94
              child: CupertinoPicker(
95 96
                scrollController: controller,
                itemExtent: 50.0,
97
                onSelectedItemChanged: (_) { },
98
                children: List<Widget>.generate(3, (int index) {
99
                  return SizedBox(
100 101
                    height: 50.0,
                    width: 300.0,
102
                    child: Text(index.toString()),
103 104 105 106 107 108 109 110 111
                  );
                }),
              ),
            ),
          ),
        ),
      );

      expect(
112
        tester.getTopLeft(find.widgetWithText(SizedBox, '1').first),
113 114 115 116 117 118 119
        const Offset(0.0, 125.0),
      );

      controller.jumpToItem(0);
      await tester.pump();

      expect(
120
        tester.getTopLeft(find.widgetWithText(SizedBox, '1').first),
121
        offsetMoreOrLessEquals(const Offset(0.0, 170.0), epsilon: 0.5),
122 123
      );
      expect(
124
        tester.getTopLeft(find.widgetWithText(SizedBox, '0').first),
125 126 127 128 129
        const Offset(0.0, 125.0),
      );
    });
  });

130 131 132 133 134 135 136 137 138 139 140 141 142
  testWidgets('picker dark mode', (WidgetTester tester) async {
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(brightness: Brightness.light),
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              backgroundColor: const CupertinoDynamicColor.withBrightness(
                color: Color(0xFF123456), // Set alpha channel to FF to disable under magnifier painting.
                darkColor: Color(0xFF654321),
143
              ),
144 145 146
              itemExtent: 15.0,
              children: const <Widget>[Text('1'), Text('1')],
              onSelectedItemChanged: (int i) { },
147 148 149
            ),
          ),
        ),
150 151
      ),
    );
152

153
    expect(find.byType(CupertinoPicker), paints..rrect(color: const Color.fromARGB(30, 118, 118, 128)));
154
    expect(find.byType(CupertinoPicker), paints..rect(color: const Color(0xFF123456)));
155

156 157 158 159 160 161 162 163 164 165 166 167
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(brightness: Brightness.dark),
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              backgroundColor: const CupertinoDynamicColor.withBrightness(
                color: Color(0xFF123456),
                darkColor: Color(0xFF654321),
168
              ),
169 170 171
              itemExtent: 15.0,
              children: const <Widget>[Text('1'), Text('1')],
              onSelectedItemChanged: (int i) { },
172 173 174
            ),
          ),
        ),
175 176 177
      ),
    );

178
    expect(find.byType(CupertinoPicker), paints..rrect(color: const Color.fromARGB(61,118, 118, 128)));
179
    expect(find.byType(CupertinoPicker), paints..rect(color: const Color(0xFF654321)));
180 181
  });

182 183 184 185 186 187 188 189 190 191 192 193
  testWidgets('picker selectionOverlay', (WidgetTester tester) async {
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(brightness: Brightness.light),
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              itemExtent: 15.0,
              onSelectedItemChanged: (int i) {},
194
              selectionOverlay: const CupertinoPickerDefaultSelectionOverlay(background: Color(0x12345678)),
195
              children: const <Widget>[Text('1'), Text('1')],
196 197 198 199 200 201 202 203 204
            ),
          ),
        ),
      ),
    );

    expect(find.byType(CupertinoPicker), paints..rrect(color: const Color(0x12345678)));
  });

205 206 207 208 209 210 211 212 213 214 215 216 217
  testWidgets('CupertinoPicker.selectionOverlay is nullable', (WidgetTester tester) async {
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(brightness: Brightness.light),
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              itemExtent: 15.0,
              onSelectedItemChanged: (int i) {},
              selectionOverlay: null,
218
              children: const <Widget>[Text('1'), Text('1')],
219 220 221 222 223 224 225 226 227
            ),
          ),
        ),
      ),
    );

    expect(find.byType(CupertinoPicker), isNot(paints..rrect()));
  });

228
  group('scroll', () {
229 230 231 232 233 234
    testWidgets(
      'scrolling calls onSelectedItemChanged and triggers haptic feedback',
      (WidgetTester tester) async {
        final List<int> selectedItems = <int>[];
        final List<MethodCall> systemCalls = <MethodCall>[];

235
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
236
          systemCalls.add(methodCall);
237
          return null;
238 239 240
        });

        await tester.pumpWidget(
241
          Directionality(
242
            textDirection: TextDirection.ltr,
243
            child: CupertinoPicker(
244 245
              itemExtent: 100.0,
              onSelectedItemChanged: (int index) { selectedItems.add(index); },
246 247
              children: List<Widget>.generate(100, (int index) {
                return Center(
248
                  child: SizedBox(
249 250
                    width: 400.0,
                    height: 100.0,
251
                    child: Text(index.toString()),
252 253 254 255 256 257 258
                  ),
                );
              }),
            ),
          ),
        );

259
        await tester.drag(find.text('0'), const Offset(0.0, -100.0), warnIfMissed: false); // has an IgnorePointer
260 261 262 263 264 265 266 267 268
        expect(selectedItems, <int>[1]);
        expect(
          systemCalls.single,
          isMethodCall(
            'HapticFeedback.vibrate',
            arguments: 'HapticFeedbackType.selectionClick',
          ),
        );

269
        await tester.drag(find.text('0'), const Offset(0.0, 100.0), warnIfMissed: false); // has an IgnorePointer
270 271 272 273 274 275 276 277 278
        expect(selectedItems, <int>[1, 0]);
        expect(systemCalls, hasLength(2));
        expect(
          systemCalls.last,
          isMethodCall(
            'HapticFeedback.vibrate',
            arguments: 'HapticFeedbackType.selectionClick',
          ),
        );
279 280 281
      },
      variant: TargetPlatformVariant.only(TargetPlatform.iOS),
    );
282 283 284 285 286 287 288

    testWidgets(
      'do not trigger haptic effects on non-iOS devices',
      (WidgetTester tester) async {
        final List<int> selectedItems = <int>[];
        final List<MethodCall> systemCalls = <MethodCall>[];

289
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
290
          systemCalls.add(methodCall);
291
          return null;
292 293 294
        });

        await tester.pumpWidget(
295
          Directionality(
296
            textDirection: TextDirection.ltr,
297
            child: CupertinoPicker(
298 299
              itemExtent: 100.0,
              onSelectedItemChanged: (int index) { selectedItems.add(index); },
300 301
              children: List<Widget>.generate(100, (int index) {
                return Center(
302
                  child: SizedBox(
303 304
                    width: 400.0,
                    height: 100.0,
305
                    child: Text(index.toString()),
306 307 308 309 310 311 312
                  ),
                );
              }),
            ),
          ),
        );

313
        await tester.drag(find.text('0'), const Offset(0.0, -100.0), warnIfMissed: false); // has an IgnorePointer
314 315
        expect(selectedItems, <int>[1]);
        expect(systemCalls, isEmpty);
316 317 318
      },
      variant: TargetPlatformVariant(TargetPlatform.values.where((TargetPlatform platform) => platform != TargetPlatform.iOS).toSet()),
    );
319

320
    testWidgets('a drag in between items settles back', (WidgetTester tester) async {
321
      final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10);
322 323 324
      final List<int> selectedItems = <int>[];

      await tester.pumpWidget(
325
        Directionality(
326
          textDirection: TextDirection.ltr,
327
          child: CupertinoPicker(
328 329 330
            scrollController: controller,
            itemExtent: 100.0,
            onSelectedItemChanged: (int index) { selectedItems.add(index); },
331 332
            children: List<Widget>.generate(100, (int index) {
              return Center(
333
                child: SizedBox(
334 335
                  width: 400.0,
                  height: 100.0,
336
                  child: Text(index.toString()),
337 338 339 340 341 342 343 344
                ),
              );
            }),
          ),
        ),
      );

      // Drag it by a bit but not enough to move to the next item.
345
      await tester.drag(find.text('10'), const Offset(0.0, 30.0), touchSlopY: 0.0, warnIfMissed: false); // has an IgnorePointer
346 347 348

      // The item that was in the center now moved a bit.
      expect(
349
        tester.getTopLeft(find.widgetWithText(SizedBox, '10')),
350
        const Offset(200.0, 250.0),
351 352 353 354 355
      );

      await tester.pumpAndSettle();

      expect(
356
        tester.getTopLeft(find.widgetWithText(SizedBox, '10')).dy,
357 358 359 360 361
        moreOrLessEquals(250.0, epsilon: 0.5),
      );
      expect(selectedItems.isEmpty, true);

      // Drag it by enough to move to the next item.
362
      await tester.drag(find.text('10'), const Offset(0.0, 70.0), touchSlopY: 0.0, warnIfMissed: false); // has an IgnorePointer
363 364 365 366

      await tester.pumpAndSettle();

      expect(
367
        tester.getTopLeft(find.widgetWithText(SizedBox, '10')).dy,
368
        // It's down by 100.0 now.
369
        moreOrLessEquals(340.0, epsilon: 0.5),
370 371
      );
      expect(selectedItems, <int>[9]);
Dan Field's avatar
Dan Field committed
372
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
373 374 375

    testWidgets('a big fling that overscrolls springs back', (WidgetTester tester) async {
      final FixedExtentScrollController controller =
376
          FixedExtentScrollController(initialItem: 10);
377 378 379
      final List<int> selectedItems = <int>[];

      await tester.pumpWidget(
380
        Directionality(
381
          textDirection: TextDirection.ltr,
382
          child: CupertinoPicker(
383 384 385
            scrollController: controller,
            itemExtent: 100.0,
            onSelectedItemChanged: (int index) { selectedItems.add(index); },
386 387
            children: List<Widget>.generate(100, (int index) {
              return Center(
388
                child: SizedBox(
389 390
                  width: 400.0,
                  height: 100.0,
391
                  child: Text(index.toString()),
392 393 394 395 396 397 398 399 400 401 402 403
                ),
              );
            }),
          ),
        ),
      );

      // A wild throw appears.
      await tester.fling(
        find.text('10'),
        const Offset(0.0, 10000.0),
        1000.0,
404
        warnIfMissed: false, // has an IgnorePointer
405 406
      );

407 408 409 410 411
      if (debugDefaultTargetPlatformOverride == TargetPlatform.iOS) {
        // Should have been flung far enough that even the first item goes off
        // screen and gets removed.
        expect(find.widgetWithText(SizedBox, '0').evaluate().isEmpty, true);
      }
412

413 414 415 416 417 418 419 420 421 422 423
      expect(
        selectedItems,
        // This specific throw was fast enough that each scroll update landed
        // on every second item.
        <int>[8, 6, 4, 2, 0],
      );

      // Let it spring back.
      await tester.pumpAndSettle();

      expect(
424
        tester.getTopLeft(find.widgetWithText(SizedBox, '0')).dy,
425 426 427 428 429 430 431 432
        // Should have sprung back to the middle now.
        moreOrLessEquals(250.0),
      );
      expect(
        selectedItems,
        // Falling back to 0 shouldn't produce more callbacks.
        <int>[8, 6, 4, 2, 0],
      );
433
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
434
  });
435 436

  testWidgets('Picker adapts to MaterialApp dark mode', (WidgetTester tester) async {
437
    Widget buildCupertinoPicker(Brightness brightness) {
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
      return MaterialApp(
        theme: ThemeData(brightness: brightness),
        home: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            height: 300.0,
            width: 300.0,
            child: CupertinoPicker(
              itemExtent: 50.0,
              onSelectedItemChanged: (_) { },
              children: List<Widget>.generate(3, (int index) {
                return SizedBox(
                  height: 50.0,
                  width: 300.0,
                  child: Text(index.toString()),
                );
              }),
            ),
          ),
        ),
      );
    }

    // CupertinoPicker with light theme.
462
    await tester.pumpWidget(buildCupertinoPicker(Brightness.light));
463 464 465 466 467 468
    RenderParagraph paragraph = tester.renderObject(find.text('1'));
    expect(paragraph.text.style!.color, CupertinoColors.label);
    // Text style should not return unresolved color.
    expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);

    // CupertinoPicker with dark theme.
469
    await tester.pumpWidget(buildCupertinoPicker(Brightness.dark));
470 471 472 473 474
    paragraph = tester.renderObject(find.text('1'));
    expect(paragraph.text.style!.color, CupertinoColors.label);
    // Text style should not return unresolved color.
    expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
  });
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

  group('CupertinoPickerDefaultSelectionOverlay', () {
    testWidgets('should be using directional decoration', (WidgetTester tester) async {
      await tester.pumpWidget(
        CupertinoApp(
          theme: const CupertinoThemeData(brightness: Brightness.light),
          home: CupertinoPicker(
            itemExtent: 15.0,
            onSelectedItemChanged: (int i) {},
            selectionOverlay: const CupertinoPickerDefaultSelectionOverlay(background: Color(0x12345678)),
            children: const <Widget>[Text('1'), Text('1')],
          ),
        ),
      );

      final Finder selectionContainer = find.byType(Container);
      final Container container = tester.firstWidget<Container>(selectionContainer);
      final EdgeInsetsGeometry? margin = container.margin;
      final BorderRadiusGeometry? borderRadius = (container.decoration as BoxDecoration?)?.borderRadius;

      expect(margin, isA<EdgeInsetsDirectional>());
      expect(borderRadius, isA<BorderRadiusDirectional>());
    });
  });
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

  testWidgets('Scroll controller is detached upon dispose', (WidgetTester tester) async {
    final SpyFixedExtentScrollController controller = SpyFixedExtentScrollController();
    expect(controller.hasListeners, false);
    expect(controller.positions.length, 0);

    await tester.pumpWidget(CupertinoApp(
      home: Align(
        alignment: Alignment.topLeft,
        child: Center(
          child: CupertinoPicker(
            scrollController: controller,
            itemExtent: 50.0,
            onSelectedItemChanged: (_) { },
            children: List<Widget>.generate(3, (int index) {
              return SizedBox(
                width: 300.0,
                child: Text(index.toString()),
              );
            }),
          ),
        ),
      ),
    ));
    expect(controller.hasListeners, true);
    expect(controller.positions.length, 1);

    await tester.pumpWidget(const SizedBox.expand());
    expect(controller.hasListeners, false);
    expect(controller.positions.length, 0);
  });

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 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  testWidgets('Registers taps and does not crash with certain diameterRatio', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/126491

    final List<int> children = List<int>.generate(100, (int index) => index);
    final List<int> paintedChildren = <int>[];
    final Set<int> tappedChildren = <int>{};

    await tester.pumpWidget(CupertinoApp(
      home: Align(
        alignment: Alignment.topLeft,
        child: Center(
          child: SizedBox(
            height: 120,
            child: CupertinoPicker(
              itemExtent: 55,
              diameterRatio: 0.9,
              onSelectedItemChanged: (int index) {},
              children: children
                .map<Widget>((int index) =>
                  GestureDetector(
                    key: ValueKey<int>(index),
                    onTap: () {
                      tappedChildren.add(index);
                    },
                    child: SizedBox(
                      width: 55,
                      height: 55,
                      child: CustomPaint(
                        painter: TestCallbackPainter(onPaint: () {
                          paintedChildren.add(index);
                        }),
                      ),
                    ),
                  ),
                )
                .toList(),
            ),
          ),
        ),
      ),
    ));

    // Children are painted two times for whatever reason
    expect(paintedChildren, <int>[0, 1, 0, 1]);

    // Expect hitting 0 and 1, which are painted
    await tester.tap(find.byKey(const ValueKey<int>(0)));
    expect(tappedChildren, const <int>[0]);

    await tester.tap(find.byKey(const ValueKey<int>(1)));
    expect(tappedChildren, const <int>[0, 1]);

    // The third child is not painted, so is not hit
    await tester.tap(find.byKey(const ValueKey<int>(2)), warnIfMissed: false);
    expect(tappedChildren, const <int>[0, 1]);
  });

588
}