slider_test.dart 103 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/cupertino.dart';
8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/gestures.dart';
10
import 'package:flutter/material.dart';
11
import 'package:flutter/rendering.dart';
12
import 'package:flutter/scheduler.dart';
13
import 'package:flutter/services.dart';
14
import 'package:flutter/src/physics/utils.dart' show nearEqual;
15 16
import 'package:flutter_test/flutter_test.dart';

17
import '../rendering/mock_canvas.dart';
18
import '../widgets/semantics_tester.dart';
19

20 21 22 23 24 25 26 27 28 29 30 31 32
// A thumb shape that also logs its repaint center.
class LoggingThumbShape extends SliderComponentShape {
  LoggingThumbShape(this.log);

  final List<Offset> log;

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return const Size(10.0, 10.0);
  }

  @override
  void paint(
33 34
    PaintingContext context,
    Offset thumbCenter, {
35 36 37 38 39 40 41 42 43 44
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
45
  }) {
46
    log.add(thumbCenter);
47
    final Paint thumbPaint = Paint()..color = Colors.red;
48 49 50 51
    context.canvas.drawCircle(thumbCenter, 5.0, thumbPaint);
  }
}

52 53
class TallSliderTickMarkShape extends SliderTickMarkShape {
  @override
54
  Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}) {
55 56 57 58 59
    return const Size(10.0, 200.0);
  }

  @override
  void paint(
60 61
    PaintingContext context,
    Offset offset, {
62 63 64 65 66 67
    required Offset thumbCenter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required bool isEnabled,
    required TextDirection textDirection,
68
  }) {
69 70 71 72 73
    final Paint paint = Paint()..color = Colors.red;
    context.canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, 10.0, 20.0), paint);
  }
}

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
class _StateDependentMouseCursor extends MaterialStateMouseCursor {
  const _StateDependentMouseCursor({
    this.disabled = SystemMouseCursors.none,
    this.dragged = SystemMouseCursors.none,
    this.hovered = SystemMouseCursors.none,
  });

  final MouseCursor disabled;
  final MouseCursor hovered;
  final MouseCursor dragged;

  @override
  MouseCursor resolve(Set<MaterialState> states) {
    if (states.contains(MaterialState.disabled)) {
      return disabled;
    }
    if (states.contains(MaterialState.dragged)) {
      return dragged;
    }
    if (states.contains(MaterialState.hovered)) {
      return hovered;
    }
    return SystemMouseCursors.none;
  }

  @override
  String get debugDescription => '_StateDependentMouseCursor';
}

103
void main() {
104
  testWidgets('Slider can move when tapped (LTR)', (WidgetTester tester) async {
105
    final Key sliderKey = UniqueKey();
106
    double value = 0.0;
107 108
    double? startValue;
    double? endValue;
109

110
    await tester.pumpWidget(
111 112 113 114 115
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    onChanged: (double newValue) {
                      setState(() {
                        value = newValue;
                      });
                    },
                    onChangeStart: (double value) {
                      startValue = value;
                    },
                    onChangeEnd: (double value) {
                      endValue = value;
                    },
132
                  ),
133
                ),
134 135 136
              );
            },
          ),
137
        ),
138
      ),
139
    );
140

141
    expect(value, equals(0.0));
142
    await tester.tap(find.byKey(sliderKey));
143
    expect(value, equals(0.5));
144 145 146 147
    expect(startValue, equals(0.0));
    expect(endValue, equals(0.5));
    startValue = null;
    endValue = null;
148
    await tester.pump(); // No animation should start.
149
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
150 151 152 153 154 155

    final Offset topLeft = tester.getTopLeft(find.byKey(sliderKey));
    final Offset bottomRight = tester.getBottomRight(find.byKey(sliderKey));

    final Offset target = topLeft + (bottomRight - topLeft) / 4.0;
    await tester.tapAt(target);
156
    expect(value, moreOrLessEquals(0.25, epsilon: 0.05));
157
    expect(startValue, equals(0.5));
158
    expect(endValue, moreOrLessEquals(0.25, epsilon: 0.05));
159
    await tester.pump(); // No animation should start.
160
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
161 162
  });

163
  testWidgets('Slider can move when tapped (RTL)', (WidgetTester tester) async {
164
    final Key sliderKey = UniqueKey();
165
    double value = 0.0;
166

167
    await tester.pumpWidget(
168 169 170 171 172
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.rtl,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
173 174 175 176 177 178 179 180 181 182
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    onChanged: (double newValue) {
                      setState(() {
                        value = newValue;
                      });
                    },
183
                  ),
184
                ),
185 186 187
              );
            },
          ),
188 189 190 191 192 193 194 195
        ),
      ),
    );

    expect(value, equals(0.0));
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
    await tester.pump(); // No animation should start.
196
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
197 198 199 200 201 202

    final Offset topLeft = tester.getTopLeft(find.byKey(sliderKey));
    final Offset bottomRight = tester.getBottomRight(find.byKey(sliderKey));

    final Offset target = topLeft + (bottomRight - topLeft) / 4.0;
    await tester.tapAt(target);
203
    expect(value, moreOrLessEquals(0.75, epsilon: 0.05));
204
    await tester.pump(); // No animation should start.
205
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
206 207
  });

208
  testWidgets("Slider doesn't send duplicate change events if tapped on the same value", (WidgetTester tester) async {
209
    final Key sliderKey = UniqueKey();
210
    double value = 0.0;
211 212
    late double startValue;
    late double endValue;
213
    int updates = 0;
214 215
    int startValueUpdates = 0;
    int endValueUpdates = 0;
216

217

218
    await tester.pumpWidget(
219 220 221 222 223
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    onChanged: (double newValue) {
                      setState(() {
                        updates++;
                        value = newValue;
                      });
                    },
                    onChangeStart: (double value) {
                      startValueUpdates++;
                      startValue = value;
                    },
                    onChangeEnd: (double value) {
                      endValueUpdates++;
                      endValue = value;
                    },
243 244
                  ),
                ),
245 246 247
              );
            },
          ),
248
        ),
249
      ),
250
    );
251

252 253 254
    expect(value, equals(0.0));
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
255 256
    expect(startValue, equals(0.0));
    expect(endValue, equals(0.5));
257 258 259 260 261
    await tester.pump();
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
    await tester.pump();
    expect(updates, equals(1));
262 263
    expect(startValueUpdates, equals(2));
    expect(endValueUpdates, equals(2));
264 265
  });

266
  testWidgets('Value indicator shows for a bit after being tapped', (WidgetTester tester) async {
267
    final Key sliderKey = UniqueKey();
268 269 270
    double value = 0.0;

    await tester.pumpWidget(
271 272 273 274 275
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
276 277 278 279 280 281 282 283 284 285 286
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    divisions: 4,
                    onChanged: (double newValue) {
                      setState(() {
                        value = newValue;
                      });
                    },
287 288
                  ),
                ),
289 290 291
              );
            },
          ),
292 293 294 295 296 297 298 299 300
        ),
      ),
    );

    expect(value, equals(0.0));
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
    await tester.pump(const Duration(milliseconds: 100));
    // Starts with the position animation and value indicator
301
    expect(SchedulerBinding.instance.transientCallbackCount, equals(2));
302 303
    await tester.pump(const Duration(milliseconds: 100));
    // Value indicator is longer than position.
304
    expect(SchedulerBinding.instance.transientCallbackCount, equals(1));
305
    await tester.pump(const Duration(milliseconds: 100));
306
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
307
    await tester.pump(const Duration(milliseconds: 100));
308
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
309 310
    await tester.pump(const Duration(milliseconds: 100));
    // Shown for long enough, value indicator is animated closed.
311
    expect(SchedulerBinding.instance.transientCallbackCount, equals(1));
312
    await tester.pump(const Duration(milliseconds: 101));
313
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
314 315 316
  });

  testWidgets('Discrete Slider repaints and animates when dragged', (WidgetTester tester) async {
317
    final Key sliderKey = UniqueKey();
318 319
    double value = 0.0;
    final List<Offset> log = <Offset>[];
320
    final LoggingThumbShape loggingThumb = LoggingThumbShape(log);
321
    await tester.pumpWidget(
322 323 324 325 326 327
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              final SliderThemeData sliderTheme = SliderTheme.of(context).copyWith(thumbShape: loggingThumb);
nt4f04uNd's avatar
nt4f04uNd committed
328 329 330 331 332 333 334 335 336 337 338 339 340
              return Material(
                child: Center(
                  child: SliderTheme(
                    data: sliderTheme,
                    child: Slider(
                      key: sliderKey,
                      value: value,
                      divisions: 4,
                      onChanged: (double newValue) {
                        setState(() {
                          value = newValue;
                        });
                      },
341 342 343
                    ),
                  ),
                ),
344 345 346
              );
            },
          ),
347 348 349 350 351
        ),
      ),
    );

    final List<Offset> expectedLog = <Offset>[
352 353
      const Offset(24.0, 300.0),
      const Offset(24.0, 300.0),
354 355 356 357 358 359 360 361 362 363 364 365 366
      const Offset(400.0, 300.0),
    ];
    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));
    expect(value, equals(0.5));
    expect(log.length, 3);
    expect(log, orderedEquals(expectedLog));
    await gesture.moveBy(const Offset(-500.0, 0.0));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
    expect(value, equals(0.0));
    expect(log.length, 5);
367
    expect(log.last.dx, moreOrLessEquals(386.6, epsilon: 0.1));
368 369 370 371 372 373
    // With no more gesture or value changes, the thumb position should still
    // be redrawn in the animated position.
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
    expect(value, equals(0.0));
    expect(log.length, 7);
374
    expect(log.last.dx, moreOrLessEquals(344.5, epsilon: 0.1));
375 376
    // Final position.
    await tester.pump(const Duration(milliseconds: 80));
377
    expectedLog.add(const Offset(24.0, 300.0));
378 379
    expect(value, equals(0.0));
    expect(log.length, 8);
380
    expect(log.last.dx, moreOrLessEquals(24.0, epsilon: 0.1));
381 382 383 384
    await gesture.up();
  });

  testWidgets("Slider doesn't send duplicate change events if tapped on the same value", (WidgetTester tester) async {
385
    final Key sliderKey = UniqueKey();
386 387 388 389
    double value = 0.0;
    int updates = 0;

    await tester.pumpWidget(
390 391 392 393 394
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
395 396 397 398 399 400 401 402 403 404 405
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    onChanged: (double newValue) {
                      setState(() {
                        updates++;
                        value = newValue;
                      });
                    },
406 407
                  ),
                ),
408 409 410
              );
            },
          ),
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
        ),
      ),
    );

    expect(value, equals(0.0));
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
    await tester.pump();
    await tester.tap(find.byKey(sliderKey));
    expect(value, equals(0.5));
    await tester.pump();
    expect(updates, equals(1));
  });

  testWidgets('discrete Slider repaints when dragged', (WidgetTester tester) async {
426
    final Key sliderKey = UniqueKey();
427 428
    double value = 0.0;
    final List<Offset> log = <Offset>[];
429
    final LoggingThumbShape loggingThumb = LoggingThumbShape(log);
430
    await tester.pumpWidget(
431 432 433 434 435 436
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              final SliderThemeData sliderTheme = SliderTheme.of(context).copyWith(thumbShape: loggingThumb);
nt4f04uNd's avatar
nt4f04uNd committed
437 438 439 440 441 442 443 444 445 446 447 448 449
              return Material(
                child: Center(
                  child: SliderTheme(
                    data: sliderTheme,
                    child: Slider(
                      key: sliderKey,
                      value: value,
                      divisions: 4,
                      onChanged: (double newValue) {
                        setState(() {
                          value = newValue;
                        });
                      },
450 451 452
                    ),
                  ),
                ),
453 454 455
              );
            },
          ),
456 457 458 459 460
        ),
      ),
    );

    final List<Offset> expectedLog = <Offset>[
461 462
      const Offset(24.0, 300.0),
      const Offset(24.0, 300.0),
463 464 465 466 467 468 469 470 471 472 473 474 475
      const Offset(400.0, 300.0),
    ];
    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));
    expect(value, equals(0.5));
    expect(log.length, 3);
    expect(log, orderedEquals(expectedLog));
    await gesture.moveBy(const Offset(-500.0, 0.0));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
    expect(value, equals(0.0));
    expect(log.length, 5);
476
    expect(log.last.dx, moreOrLessEquals(386.6, epsilon: 0.1));
477 478 479 480 481 482
    // With no more gesture or value changes, the thumb position should still
    // be redrawn in the animated position.
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
    expect(value, equals(0.0));
    expect(log.length, 7);
483
    expect(log.last.dx, moreOrLessEquals(344.5, epsilon: 0.1));
484 485
    // Final position.
    await tester.pump(const Duration(milliseconds: 80));
486
    expectedLog.add(const Offset(24.0, 300.0));
487 488
    expect(value, equals(0.0));
    expect(log.length, 8);
489
    expect(log.last.dx, moreOrLessEquals(24.0, epsilon: 0.1));
490 491 492 493
    await gesture.up();
  });

  testWidgets('Slider take on discrete values', (WidgetTester tester) async {
494
    final Key sliderKey = UniqueKey();
495 496 497
    double value = 0.0;

    await tester.pumpWidget(
498 499 500 501 502
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516
              return Material(
                child: Center(
                  child: SizedBox(
                    width: 144.0 + 2 * 16.0, // _kPreferredTotalWidth
                    child: Slider(
                      key: sliderKey,
                      max: 100.0,
                      divisions: 10,
                      value: value,
                      onChanged: (double newValue) {
                        setState(() {
                          value = newValue;
                        });
                      },
517 518 519
                    ),
                  ),
                ),
520 521 522
              );
            },
          ),
523 524 525 526
        ),
      ),
    );

527
    expect(value, equals(0.0));
528
    await tester.tap(find.byKey(sliderKey));
529
    expect(value, equals(50.0));
530
    await tester.drag(find.byKey(sliderKey), const Offset(5.0, 0.0));
531
    expect(value, equals(50.0));
532
    await tester.drag(find.byKey(sliderKey), const Offset(40.0, 0.0));
533
    expect(value, equals(80.0));
534

535
    await tester.pump(); // Starts animation.
536
    expect(SchedulerBinding.instance.transientCallbackCount, greaterThan(0));
537 538 539 540
    await tester.pump(const Duration(milliseconds: 200));
    await tester.pump(const Duration(milliseconds: 200));
    await tester.pump(const Duration(milliseconds: 200));
    await tester.pump(const Duration(milliseconds: 200));
541
    // Animation complete.
542
    expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
543
  });
544

545
  testWidgets('Slider can be given zero values', (WidgetTester tester) async {
546
    final List<double> log = <double>[];
547 548 549 550
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
551 552 553 554 555 556
          child: Material(
            child: Slider(
              value: 0.0,
              onChanged: (double newValue) {
                log.add(newValue);
              },
557
            ),
558
          ),
559
        ),
560
      ),
561
    );
562 563 564 565 566

    await tester.tap(find.byType(Slider));
    expect(log, <double>[0.5]);
    log.clear();

567 568 569 570
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
571 572 573 574 575 576 577
          child: Material(
            child: Slider(
              value: 0.0,
              max: 0.0,
              onChanged: (double newValue) {
                log.add(newValue);
              },
578
            ),
579 580 581 582 583 584 585
          ),
        ),
      ),
    );

    await tester.tap(find.byType(Slider));
    expect(log, <double>[]);
586 587
    log.clear();
  });
588

589
  testWidgets('Slider uses the right theme colors for the right components', (WidgetTester tester) async {
590 591
    const Color customColor1 = Color(0xcafefeed);
    const Color customColor2 = Color(0xdeadbeef);
592
    final ThemeData theme = ThemeData(
593 594
      platform: TargetPlatform.android,
      primarySwatch: Colors.blue,
595 596 597 598 599 600 601 602 603 604 605 606 607
      sliderTheme: const SliderThemeData(
        disabledThumbColor: Color(0xff000001),
        disabledActiveTickMarkColor: Color(0xff000002),
        disabledActiveTrackColor: Color(0xff000003),
        disabledInactiveTickMarkColor: Color(0xff000004),
        disabledInactiveTrackColor: Color(0xff000005),
        activeTrackColor: Color(0xff000006),
        activeTickMarkColor: Color(0xff000007),
        inactiveTrackColor: Color(0xff000008),
        inactiveTickMarkColor: Color(0xff000009),
        overlayColor: Color(0xff000010),
        thumbColor: Color(0xff000011),
        valueIndicatorColor: Color(0xff000012),
608
      ),
609 610 611 612
    );
    final SliderThemeData sliderTheme = theme.sliderTheme;
    double value = 0.45;
    Widget buildApp({
613 614 615
      Color? activeColor,
      Color? inactiveColor,
      int? divisions,
616
      bool enabled = true,
617
    }) {
618
      final ValueChanged<double>? onChanged = !enabled
619 620 621 622
        ? null
        : (double d) {
            value = d;
          };
623 624 625
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
626 627 628 629 630 631 632 633 634 635 636
          child: Material(
            child: Center(
              child: Theme(
                data: theme,
                child: Slider(
                  value: value,
                  label: '$value',
                  divisions: divisions,
                  activeColor: activeColor,
                  inactiveColor: inactiveColor,
                  onChanged: onChanged,
Jose Alba's avatar
Jose Alba committed
637 638 639 640 641 642 643 644 645 646
                ),
              ),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildApp());

647
    final MaterialInkController material = Material.of(tester.element(find.byType(Slider)))!;
648
    final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
649 650

    // Check default theme for enabled widget.
651 652 653 654 655 656 657 658
    expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: sliderTheme.inactiveTrackColor));
    expect(material, paints..shadow(color: const Color(0xff000000)));
    expect(material, paints..circle(color: sliderTheme.thumbColor));
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
659 660 661

    // Test setting only the activeColor.
    await tester.pumpWidget(buildApp(activeColor: customColor1));
662 663 664 665 666 667 668
    expect(material, paints..rrect(color: customColor1)..rrect(color: sliderTheme.inactiveTrackColor));
    expect(material, paints..shadow(color: Colors.black));
    expect(material, paints..circle(color: customColor1));
    expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
669 670 671

    // Test setting only the inactiveColor.
    await tester.pumpWidget(buildApp(inactiveColor: customColor1));
672 673 674 675 676 677
    expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: customColor1));
    expect(material, paints..shadow(color: Colors.black));
    expect(material, paints..circle(color: sliderTheme.thumbColor));
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
678 679 680

    // Test setting both activeColor and inactiveColor.
    await tester.pumpWidget(buildApp(activeColor: customColor1, inactiveColor: customColor2));
681 682 683 684 685 686 687
    expect(material, paints..rrect(color: customColor1)..rrect(color: customColor2));
    expect(material, paints..shadow(color: Colors.black));
    expect(material, paints..circle(color: customColor1));
    expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
688 689 690

    // Test colors for discrete slider.
    await tester.pumpWidget(buildApp(divisions: 3));
691
    expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: sliderTheme.inactiveTrackColor));
692
    expect(
693 694 695 696 697 698 699 700
      material,
      paints
        ..circle(color: sliderTheme.activeTickMarkColor)
        ..circle(color: sliderTheme.activeTickMarkColor)
        ..circle(color: sliderTheme.inactiveTickMarkColor)
        ..circle(color: sliderTheme.inactiveTickMarkColor)
        ..shadow(color: Colors.black)
        ..circle(color: sliderTheme.thumbColor),
701
    );
702 703 704
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
705 706 707 708 709 710 711

    // Test colors for discrete slider with inactiveColor and activeColor set.
    await tester.pumpWidget(buildApp(
      activeColor: customColor1,
      inactiveColor: customColor2,
      divisions: 3,
    ));
712
    expect(material, paints..rrect(color: customColor1)..rrect(color: customColor2));
713
    expect(
714 715 716 717 718 719 720 721 722
      material,
      paints
        ..circle(color: customColor2)
        ..circle(color: customColor2)
        ..circle(color: customColor1)
        ..circle(color: customColor1)
        ..shadow(color: Colors.black)
        ..circle(color: customColor1),
    );
723 724 725 726 727 728
    expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
    expect(material, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
729 730 731 732 733

    // Test default theme for disabled widget.
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(
734 735 736 737 738
      material,
      paints
        ..rrect(color: sliderTheme.disabledActiveTrackColor)
        ..rrect(color: sliderTheme.disabledInactiveTrackColor),
    );
739 740 741 742
    expect(material, paints..shadow(color: Colors.black)..circle(color: sliderTheme.disabledThumbColor));
    expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.activeTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.inactiveTrackColor)));
743 744 745 746

    // Test setting the activeColor and inactiveColor for disabled widget.
    await tester.pumpWidget(buildApp(activeColor: customColor1, inactiveColor: customColor2, enabled: false));
    expect(
747 748 749 750 751
      material,
      paints
        ..rrect(color: sliderTheme.disabledActiveTrackColor)
        ..rrect(color: sliderTheme.disabledInactiveTrackColor),
    );
752 753 754 755
    expect(material, paints..circle(color: sliderTheme.disabledThumbColor));
    expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.activeTrackColor)));
    expect(material, isNot(paints..rrect(color: sliderTheme.inactiveTrackColor)));
756 757 758 759 760 761 762 763 764 765 766

    // Test that the default value indicator has the right colors.
    await tester.pumpWidget(buildApp(divisions: 3));
    Offset center = tester.getCenter(find.byType(Slider));
    TestGesture gesture = await tester.startGesture(center);
    // Wait for value indicator animation to finish.
    await tester.pumpAndSettle();
    expect(value, equals(2.0 / 3.0));
    expect(
      valueIndicatorBox,
      paints
767 768
        ..path(color: sliderTheme.valueIndicatorColor)
        ..paragraph(),
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    );
    await gesture.up();
    // Wait for value indicator animation to finish.
    await tester.pumpAndSettle();

    // Testing the custom colors are used for the indicator.
    await tester.pumpWidget(buildApp(
      divisions: 3,
      activeColor: customColor1,
      inactiveColor: customColor2,
    ));
    center = tester.getCenter(find.byType(Slider));
    gesture = await tester.startGesture(center);
    // Wait for value indicator animation to finish.
    await tester.pumpAndSettle();
    expect(value, equals(2.0 / 3.0));
    expect(
      valueIndicatorBox,
      paints
788
        ..rrect(color: const Color(0xfffafafa))
789 790 791 792 793 794 795 796 797 798 799 800 801 802
        ..rrect(color: customColor1) // active track
        ..rrect(color: customColor2) // inactive track
        ..circle(color: customColor1.withOpacity(0.12)) // overlay
        ..circle(color: customColor2) // 1st tick mark
        ..circle(color: customColor2) // 2nd tick mark
        ..circle(color: customColor2) // 3rd tick mark
        ..circle(color: customColor1) // 4th tick mark
        ..shadow(color: Colors.black)
        ..circle(color: customColor1) // thumb
        ..path(color: sliderTheme.valueIndicatorColor), // indicator
    );
    await gesture.up();
  });

803
  testWidgets('Slider can tap in vertical scroller', (WidgetTester tester) async {
804
    double value = 0.0;
805 806 807 808
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
809 810 811 812 813 814 815 816 817 818 819 820 821
          child: Material(
            child: ListView(
              children: <Widget>[
                Slider(
                  value: value,
                  onChanged: (double newValue) {
                    value = newValue;
                  },
                ),
                Container(
                  height: 2000.0,
                ),
              ],
822
            ),
823
          ),
824 825
        ),
      ),
826
    );
827 828 829 830 831 832 833

    await tester.tap(find.byType(Slider));
    expect(value, equals(0.5));
  });

  testWidgets('Slider drags immediately (LTR)', (WidgetTester tester) async {
    double value = 0.0;
834 835 836 837
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
838 839 840 841 842 843 844
          child: Material(
            child: Center(
              child: Slider(
                value: value,
                onChanged: (double newValue) {
                  value = newValue;
                },
845
              ),
846
            ),
847
          ),
848
        ),
849
      ),
850
    );
851

852 853 854
    final Offset center = tester.getCenter(find.byType(Slider));
    final TestGesture gesture = await tester.startGesture(center);

855
    expect(value, equals(0.5));
856 857 858 859 860 861

    await gesture.moveBy(const Offset(1.0, 0.0));

    expect(value, greaterThan(0.5));

    await gesture.up();
862 863
  });

864
  testWidgets('Slider drags immediately (RTL)', (WidgetTester tester) async {
865
    double value = 0.0;
866 867 868 869
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.rtl,
nt4f04uNd's avatar
nt4f04uNd committed
870 871 872 873 874 875 876
          child: Material(
            child: Center(
              child: Slider(
                value: value,
                onChanged: (double newValue) {
                  value = newValue;
                },
877
              ),
878
            ),
879
          ),
880 881
        ),
      ),
882
    );
883

884
    final Offset center = tester.getCenter(find.byType(Slider));
885
    final TestGesture gesture = await tester.startGesture(center);
886 887 888

    expect(value, equals(0.5));

889
    await gesture.moveBy(const Offset(1.0, 0.0));
890

891
    expect(value, lessThan(0.5));
892 893 894

    await gesture.up();
  });
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
  testWidgets('Slider onChangeStart and onChangeEnd fire once', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/28115

    int startFired = 0;
    int endFired = 0;
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: GestureDetector(
                onHorizontalDragUpdate: (_) { },
                child: Slider(
                  value: 0.0,
                  onChanged: (double newValue) { },
                  onChangeStart: (double value) {
                    startFired += 1;
                  },
                  onChangeEnd: (double value) {
                    endFired += 1;
                  },
                ),
              ),
            ),
          ),
        ),
      ),
    );

    await tester.timedDrag(
      find.byType(Slider),
      const Offset(20.0, 0.0),
      const Duration(milliseconds: 100),
    );

    expect(startFired, equals(1));
    expect(endFired, equals(1));
  });

936
  testWidgets('Slider sizing', (WidgetTester tester) async {
937
    await tester.pumpWidget(
nt4f04uNd's avatar
nt4f04uNd committed
938
      const MaterialApp(
939 940
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
941 942 943 944 945
          child: Material(
            child: Center(
              child: Slider(
                value: 0.5,
                onChanged: null,
946
              ),
947
            ),
948
          ),
949 950
        ),
      ),
951
    );
952 953
    expect(tester.renderObject<RenderBox>(find.byType(Slider)).size, const Size(800.0, 600.0));

954
    await tester.pumpWidget(
nt4f04uNd's avatar
nt4f04uNd committed
955
      const MaterialApp(
956 957
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
958 959 960 961 962 963
          child: Material(
            child: Center(
              child: IntrinsicWidth(
                child: Slider(
                  value: 0.5,
                  onChanged: null,
964
                ),
965
              ),
966
            ),
967 968 969
          ),
        ),
      ),
970
    );
971
    expect(tester.renderObject<RenderBox>(find.byType(Slider)).size, const Size(144.0 + 2.0 * 24.0, 600.0));
972

973
    await tester.pumpWidget(
nt4f04uNd's avatar
nt4f04uNd committed
974
      const MaterialApp(
975 976
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
977 978 979 980 981 982 983 984
          child: Material(
            child: Center(
              child: OverflowBox(
                maxWidth: double.infinity,
                maxHeight: double.infinity,
                child: Slider(
                  value: 0.5,
                  onChanged: null,
985
                ),
986
              ),
987
            ),
988 989 990
          ),
        ),
      ),
991
    );
992
    expect(tester.renderObject<RenderBox>(find.byType(Slider)).size, const Size(144.0 + 2.0 * 24.0, 48.0));
993
  });
994

995
  testWidgets('Slider respects textScaleFactor', (WidgetTester tester) async {
Jose Alba's avatar
Jose Alba committed
996 997 998 999
    final Key sliderKey = UniqueKey();
    double value = 0.0;

    Widget buildSlider({
1000
      required double textScaleFactor,
Jose Alba's avatar
Jose Alba committed
1001 1002 1003
      bool isDiscrete = true,
      ShowValueIndicator show = ShowValueIndicator.onlyForDiscrete,
    }) {
1004 1005 1006 1007 1008 1009 1010 1011 1012
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return MediaQuery(
                data: MediaQueryData(textScaleFactor: textScaleFactor),
                child: Material(
                  child: Theme(
1013 1014
                    data: Theme.of(context).copyWith(
                      sliderTheme: Theme.of(context).sliderTheme.copyWith(showValueIndicator: show),
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
                    ),
                    child: Center(
                      child: OverflowBox(
                        maxWidth: double.infinity,
                        maxHeight: double.infinity,
                        child: Slider(
                          key: sliderKey,
                          max: 100.0,
                          divisions: isDiscrete ? 10 : null,
                          label: '${value.round()}',
                          value: value,
                          onChanged: (double newValue) {
                            setState(() {
                              value = newValue;
                            });
                          },
                        ),
                      ),
                    ),
1034
                  ),
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
                ),
              );
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildSlider(textScaleFactor: 1.0));
    Offset center = tester.getCenter(find.byType(Slider));
    TestGesture gesture = await tester.startGesture(center);
    await tester.pumpAndSettle();

    expect(
1049
      tester.renderObject(find.byType(Overlay)),
1050 1051 1052
      paints
        ..path(
          includes: const <Offset>[
1053
            Offset.zero,
1054 1055 1056
            Offset(0.0, -8.0),
            Offset(-276.0, -16.0),
            Offset(-216.0, -16.0),
1057 1058
          ],
          color: const Color(0xf55f5f5f),
1059 1060
        )
        ..paragraph(),
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    );

    await gesture.up();
    await tester.pumpAndSettle();

    await tester.pumpWidget(buildSlider(textScaleFactor: 2.0));
    center = tester.getCenter(find.byType(Slider));
    gesture = await tester.startGesture(center);
    await tester.pumpAndSettle();

    expect(
1072
      tester.renderObject(find.byType(Overlay)),
1073 1074 1075
      paints
        ..path(
          includes: const <Offset>[
1076
            Offset.zero,
1077 1078 1079
            Offset(0.0, -8.0),
            Offset(-304.0, -16.0),
            Offset(-216.0, -16.0),
1080 1081
          ],
          color: const Color(0xf55f5f5f),
1082 1083
        )
        ..paragraph(),
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    );

    await gesture.up();
    await tester.pumpAndSettle();

    // Check continuous
    await tester.pumpWidget(buildSlider(
      textScaleFactor: 1.0,
      isDiscrete: false,
      show: ShowValueIndicator.onlyForContinuous,
    ));
    center = tester.getCenter(find.byType(Slider));
    gesture = await tester.startGesture(center);
    await tester.pumpAndSettle();

1099
    expect(tester.renderObject(find.byType(Overlay)),
1100 1101 1102
      paints
        ..path(
          includes: const <Offset>[
1103
            Offset.zero,
1104 1105 1106
            Offset(0.0, -8.0),
            Offset(-276.0, -16.0),
            Offset(-216.0, -16.0),
1107 1108
          ],
          color: const Color(0xf55f5f5f),
1109 1110
        )
        ..paragraph(),
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    );

    await gesture.up();
    await tester.pumpAndSettle();

    await tester.pumpWidget(buildSlider(
      textScaleFactor: 2.0,
      isDiscrete: false,
      show: ShowValueIndicator.onlyForContinuous,
    ));
    center = tester.getCenter(find.byType(Slider));
    gesture = await tester.startGesture(center);
    await tester.pumpAndSettle();

    expect(
1126
      tester.renderObject(find.byType(Overlay)),
1127 1128 1129
      paints
        ..path(
          includes: const <Offset>[
1130
            Offset.zero,
1131 1132 1133
            Offset(0.0, -8.0),
            Offset(-276.0, -16.0),
            Offset(-216.0, -16.0),
1134 1135
          ],
          color: const Color(0xf55f5f5f),
1136 1137
        )
        ..paragraph(),
1138
    );
1139 1140

    await gesture.up();
1141
    await tester.pumpAndSettle();
1142
  });
1143

1144 1145
  testWidgets('Tick marks are skipped when they are too dense', (WidgetTester tester) async {
    Widget buildSlider({
1146
      required int divisions,
1147
    }) {
1148 1149 1150
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1151 1152 1153 1154 1155 1156 1157
          child: Material(
            child: Center(
              child: Slider(
                max: 100.0,
                divisions: divisions,
                value: 0.25,
                onChanged: (double newValue) { },
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
              ),
            ),
          ),
        ),
      );
    }

    // Pump a slider with a reasonable amount of divisions to verify that the
    // tick marks are drawn when the number of tick marks is not too dense.
    await tester.pumpWidget(
      buildSlider(
        divisions: 4,
      ),
    );

1173
    final MaterialInkController material = Material.of(tester.element(find.byType(Slider)))!;
1174 1175

    // 5 tick marks and a thumb.
1176
    expect(material, paintsExactlyCountTimes(#drawCircle, 6));
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

    // 200 divisions will produce a tick interval off less than 6,
    // which would be too dense to draw.
    await tester.pumpWidget(
      buildSlider(
        divisions: 200,
      ),
    );

    // No tick marks are drawn because they are too dense, but the thumb is
    // still drawn.
1188
    expect(material, paintsExactlyCountTimes(#drawCircle, 1));
1189 1190
  });

1191
  testWidgets('Slider has correct animations when reparented', (WidgetTester tester) async {
Jose Alba's avatar
Jose Alba committed
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    final Key sliderKey = GlobalKey(debugLabel: 'A');
    double value = 0.0;

    Widget buildSlider(int parents) {
      Widget createParents(int parents, StateSetter setState) {
        Widget slider = Slider(
          key: sliderKey,
          value: value,
          divisions: 4,
          onChanged: (double newValue) {
            setState(() {
              value = newValue;
            });
1205
          },
Jose Alba's avatar
Jose Alba committed
1206 1207 1208 1209 1210 1211 1212 1213
        );

        for (int i = 0; i < parents; ++i) {
          slider = Column(children: <Widget>[slider]);
        }
        return slider;
      }

1214 1215 1216 1217 1218
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
1219 1220
              return Material(
                child: createParents(parents, setState),
1221 1222 1223 1224 1225 1226 1227 1228
              );
            },
          ),
        ),
      );
    }

    Future<void> testReparenting(bool reparent) async {
1229
      final MaterialInkController material = Material.of(tester.element(find.byType(Slider)))!;
1230 1231 1232 1233 1234 1235
      final Offset center = tester.getCenter(find.byType(Slider));
      // Move to 0.0.
      TestGesture gesture = await tester.startGesture(Offset.zero);
      await tester.pump();
      await gesture.up();
      await tester.pumpAndSettle();
1236
      expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
1237
      expect(
1238
        material,
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        paints
          ..circle(x: 26.0, y: 24.0, radius: 1.0)
          ..circle(x: 213.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 1.0)
          ..circle(x: 587.0, y: 24.0, radius: 1.0)
          ..circle(x: 774.0, y: 24.0, radius: 1.0)
          ..circle(x: 24.0, y: 24.0, radius: 10.0),
      );

      gesture = await tester.startGesture(center);
      await tester.pump();
      // Wait for animations to start.
      await tester.pump(const Duration(milliseconds: 25));
1252
      expect(SchedulerBinding.instance.transientCallbackCount, equals(2));
1253
      expect(
1254
        material,
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        paints
          ..circle(x: 111.20703125, y: 24.0, radius: 5.687664985656738)
          ..circle(x: 26.0, y: 24.0, radius: 1.0)
          ..circle(x: 213.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 1.0)
          ..circle(x: 587.0, y: 24.0, radius: 1.0)
          ..circle(x: 774.0, y: 24.0, radius: 1.0)
          ..circle(x: 111.20703125, y: 24.0, radius: 10.0),
      );

      // Reparenting in the middle of an animation should do nothing.
      if (reparent) {
        await tester.pumpWidget(buildSlider(2));
      }

      // Move a little further in the animations.
      await tester.pump(const Duration(milliseconds: 10));
1272
      expect(SchedulerBinding.instance.transientCallbackCount, equals(2));
1273
      expect(
1274
        material,
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        paints
          ..circle(x: 190.0135726928711, y: 24.0, radius: 12.0)
          ..circle(x: 26.0, y: 24.0, radius: 1.0)
          ..circle(x: 213.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 1.0)
          ..circle(x: 587.0, y: 24.0, radius: 1.0)
          ..circle(x: 774.0, y: 24.0, radius: 1.0)
          ..circle(x: 190.0135726928711, y: 24.0, radius: 10.0),
      );
      // Wait for animations to finish.
      await tester.pumpAndSettle();
1286
      expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
1287
      expect(
1288
        material,
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        paints
          ..circle(x: 400.0, y: 24.0, radius: 24.0)
          ..circle(x: 26.0, y: 24.0, radius: 1.0)
          ..circle(x: 213.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 1.0)
          ..circle(x: 587.0, y: 24.0, radius: 1.0)
          ..circle(x: 774.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 10.0),
      );
      await gesture.up();
      await tester.pumpAndSettle();
1300
      expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
1301
      expect(
1302
        material,
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        paints
          ..circle(x: 26.0, y: 24.0, radius: 1.0)
          ..circle(x: 213.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 1.0)
          ..circle(x: 587.0, y: 24.0, radius: 1.0)
          ..circle(x: 774.0, y: 24.0, radius: 1.0)
          ..circle(x: 400.0, y: 24.0, radius: 10.0),
      );
    }

    await tester.pumpWidget(buildSlider(1));
    // Do it once without reparenting in the middle of an animation
    await testReparenting(false);
    // Now do it again with reparenting in the middle of an animation.
    await testReparenting(true);
  });


1321
  testWidgets('Slider Semantics', (WidgetTester tester) async {
1322
    final SemanticsTester semantics = SemanticsTester(tester);
1323

1324 1325 1326
    await tester.pumpWidget(MaterialApp(
      home: Directionality(
        textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1327 1328 1329 1330
        child: Material(
          child: Slider(
            value: 0.5,
            onChanged: (double v) { },
1331
          ),
1332 1333
        ),
      ),
1334
    ));
1335

1336 1337
    await tester.pumpAndSettle();

1338
    expect(
1339 1340 1341 1342 1343
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
1344
              id: 1,
1345
              textDirection: TextDirection.ltr,
1346 1347 1348 1349 1350 1351
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
1352 1353 1354 1355
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
                            SemanticsFlag.isEnabled,
                            SemanticsFlag.isFocusable,
                            SemanticsFlag.isSlider,
                          ],
                          actions: <SemanticsAction>[
                            SemanticsAction.increase,
                            SemanticsAction.decrease,
                          ],
1366 1367 1368 1369 1370 1371
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
1372 1373 1374 1375
                    ),
                  ],
                ),
              ],
1376
            ),
1377 1378 1379 1380 1381 1382
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );
1383 1384

    // Disable slider
nt4f04uNd's avatar
nt4f04uNd committed
1385
    await tester.pumpWidget(const MaterialApp(
1386 1387
      home: Directionality(
        textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1388 1389 1390 1391
        child: Material(
          child: Slider(
            value: 0.5,
            onChanged: null,
1392
          ),
1393 1394
        ),
      ),
1395
    ));
1396

1397
    expect(
1398 1399 1400 1401 1402
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
1403 1404 1405 1406 1407
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
1408 1409
                  children: <TestSemantics>[
                    TestSemantics(
1410
                      id: 3,
1411 1412 1413 1414
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
1415 1416 1417 1418
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
                            // isFocusable is delayed by 1 frame.
                            SemanticsFlag.isFocusable,
1419
                            SemanticsFlag.isSlider,
1420
                          ],
1421 1422 1423 1424 1425 1426
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
1427 1428
                    ),
                  ],
1429 1430 1431
                ),
              ],
            ),
1432 1433 1434 1435 1436 1437
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

    await tester.pump();
    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
1460
                            SemanticsFlag.isSlider,
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                          ],
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );

1480
    semantics.dispose();
1481
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android,  TargetPlatform.fuchsia, TargetPlatform.linux }));
1482

1483 1484
  testWidgets('Slider Semantics', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);
1485

1486
    await tester.pumpWidget(
1487 1488 1489 1490 1491
      MaterialApp(
        home: Theme(
          data: ThemeData.light(),
          child: Directionality(
            textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1492 1493 1494 1495 1496
            child: Material(
              child: Slider(
                value: 100.0,
                max: 200.0,
                onChanged: (double v) { },
1497 1498 1499
              ),
            ),
          ),
1500 1501
        ),
      ),
1502 1503 1504 1505 1506 1507
    );

    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
1508 1509
          children: <TestSemantics>[
            TestSemantics(
1510 1511
              id: 1,
              textDirection: TextDirection.ltr,
1512 1513
              children: <TestSemantics>[
                TestSemantics(
1514 1515 1516 1517
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
1518 1519 1520 1521
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
1522
                          flags: <SemanticsFlag>[SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isSlider],
1523 1524 1525 1526 1527 1528 1529
                          actions: <SemanticsAction>[SemanticsAction.increase, SemanticsAction.decrease],
                          value: '50%',
                          increasedValue: '60%',
                          decreasedValue: '40%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );

    // Disable slider
nt4f04uNd's avatar
nt4f04uNd committed
1543
    await tester.pumpWidget(const MaterialApp(
1544 1545
      home: Directionality(
        textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1546 1547 1548 1549
        child: Material(
          child: Slider(
            value: 0.5,
            onChanged: null,
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
          ),
        ),
      ),
    ));

    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
1568 1569 1570 1571 1572
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 5,
1573
                          flags: <SemanticsFlag>[SemanticsFlag.hasEnabledState, SemanticsFlag.isSlider],
1574 1575 1576 1577 1578 1579
                          value: '50%',
                          increasedValue: '60%',
                          decreasedValue: '40%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
1580 1581
                    ),
                  ],
1582 1583 1584 1585 1586
                ),
              ],
            ),
          ],
        ),
1587 1588 1589 1590 1591 1592
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );
    semantics.dispose();
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
1593

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
  testWidgets('Slider Semantics', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);

    await tester.pumpWidget(MaterialApp(
      home: Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Slider(
            value: 0.5,
            onChanged: (double v) { },
          ),
        ),
      ),
    ));

    await tester.pumpAndSettle();

    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
                            SemanticsFlag.isEnabled,
                            SemanticsFlag.isFocusable,
                            SemanticsFlag.isSlider,
                          ],
                          actions: <SemanticsAction>[
                            SemanticsAction.increase,
                            SemanticsAction.decrease,
                            SemanticsAction.didGainAccessibilityFocus,
                          ],
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );

    // Disable slider
    await tester.pumpWidget(const MaterialApp(
      home: Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Slider(
            value: 0.5,
            onChanged: null,
          ),
        ),
      ),
    ));

    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
                            // isFocusable is delayed by 1 frame.
                            SemanticsFlag.isFocusable,
                            SemanticsFlag.isSlider,
                          ],
                          actions: <SemanticsAction>[
                            SemanticsAction.didGainAccessibilityFocus,
                          ],
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );

    await tester.pump();
    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
                          flags: <SemanticsFlag>[
                            SemanticsFlag.hasEnabledState,
                            SemanticsFlag.isSlider,
                          ],
                          actions: <SemanticsAction>[
                            SemanticsAction.didGainAccessibilityFocus,
                          ],
                          value: '50%',
                          increasedValue: '55%',
                          decreasedValue: '45%',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );

    semantics.dispose();
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }));

1763
  testWidgets('Slider semantics with custom formatter', (WidgetTester tester) async {
1764
    final SemanticsTester semantics = SemanticsTester(tester);
1765

1766 1767 1768
    await tester.pumpWidget(MaterialApp(
      home: Directionality(
        textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
1769 1770 1771 1772 1773 1774 1775
        child: Material(
          child: Slider(
            value: 40.0,
            max: 200.0,
            divisions: 10,
            semanticFormatterCallback: (double value) => value.round().toString(),
            onChanged: (double v) { },
1776 1777 1778 1779 1780
          ),
        ),
      ),
    ));

1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    expect(
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
              id: 1,
              textDirection: TextDirection.ltr,
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
                          flags: <SemanticsFlag>[SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isSlider],
                          actions: <SemanticsAction>[SemanticsAction.increase, SemanticsAction.decrease],
                          value: '40',
                          increasedValue: '60',
                          decreasedValue: '20',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );
    semantics.dispose();
  });

  // Regression test for https://github.com/flutter/flutter/issues/101868
  testWidgets('Slider.label info should not write to semantic node', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);

    await tester.pumpWidget(MaterialApp(
      home: Directionality(
        textDirection: TextDirection.ltr,
        child: Material(
          child: Slider(
            value: 40.0,
            max: 200.0,
            divisions: 10,
            semanticFormatterCallback: (double value) => value.round().toString(),
            onChanged: (double v) { },
            label: 'Bingo',
          ),
        ),
      ),
    ));

1841
    expect(
1842 1843 1844 1845 1846
      semantics,
      hasSemantics(
        TestSemantics.root(
          children: <TestSemantics>[
            TestSemantics(
1847
              id: 1,
1848
              textDirection: TextDirection.ltr,
1849 1850 1851 1852 1853 1854
              children: <TestSemantics>[
                TestSemantics(
                  id: 2,
                  children: <TestSemantics>[
                    TestSemantics(
                      id: 3,
1855 1856 1857 1858
                      flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                      children: <TestSemantics>[
                        TestSemantics(
                          id: 4,
1859
                          flags: <SemanticsFlag>[SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isSlider],
1860 1861 1862 1863 1864 1865 1866
                          actions: <SemanticsAction>[SemanticsAction.increase, SemanticsAction.decrease],
                          value: '40',
                          increasedValue: '60',
                          decreasedValue: '20',
                          textDirection: TextDirection.ltr,
                        ),
                      ],
1867 1868 1869 1870
                    ),
                  ],
                ),
              ],
1871
            ),
1872 1873 1874 1875 1876 1877
          ],
        ),
        ignoreRect: true,
        ignoreTransform: true,
      ),
    );
1878 1879 1880
    semantics.dispose();
  });

1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
  testWidgets('Slider is focusable and has correct focus color', (WidgetTester tester) async {
    final FocusNode focusNode = FocusNode(debugLabel: 'Slider');
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return SliderTheme(
                data: SliderThemeData(
                  overlayColor: Colors.orange[500],
                ),
                child: Slider(
                  value: value,
                  onChanged: enabled ? (double newValue) {
                    setState(() {
                      value = newValue;
                    });
                  } : null,
                  autofocus: true,
                  focusNode: focusNode,
                ),
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());

    // Check that the overlay shows when focused.
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isTrue);
    expect(
      Material.of(tester.element(find.byType(Slider))),
      paints..circle(color: Colors.orange[500]),
    );

    // Check that the overlay does not show when focused and disabled.
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(focusNode.hasPrimaryFocus, isFalse);
    expect(
      Material.of(tester.element(find.byType(Slider))),
      isNot(paints..circle(color: Colors.orange[500])),
    );
  });

  testWidgets('Slider can be hovered and has correct hover color', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    Widget buildApp({bool enabled = true}) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return SliderTheme(
                data: SliderThemeData(
                  overlayColor: Colors.orange[500],
                ),
                child: Slider(
                  value: value,
                  onChanged: enabled ? (double newValue) {
                    setState(() {
                      value = newValue;
                    });
                  } : null,
                ),
              );
            }),
          ),
        ),
      );
    }
    await tester.pumpWidget(buildApp());

    // Slider does not have overlay when enabled and not hovered.
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Slider))),
      isNot(paints..circle(color: Colors.orange[500])),
    );

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

    // Slider has overlay when enabled and hovering.
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Slider))),
      paints..circle(color: Colors.orange[500]),
    );

    // Slider does not have an overlay when disabled and hovering.
    await tester.pumpWidget(buildApp(enabled: false));
    await tester.pumpAndSettle();
    expect(
      Material.of(tester.element(find.byType(Slider))),
      isNot(paints..circle(color: Colors.orange[500])),
    );
  });

  testWidgets('Slider can be incremented and decremented by keyboard shortcuts - LTR', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Slider(
                value: value,
                onChanged: (double newValue) {
                  setState(() {
                    value = newValue;
                  });
                },
                autofocus: true,
              );
            }),
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(value, 0.55);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(value, 0.5);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
    await tester.pumpAndSettle();
    expect(value, 0.55);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.pumpAndSettle();
    expect(value, 0.5);
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android,  TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }));

  testWidgets('Slider can be incremented and decremented by keyboard shortcuts - LTR', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Slider(
                value: value,
                onChanged: (double newValue) {
                  setState(() {
                    value = newValue;
                  });
                },
                autofocus: true,
              );
            }),
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(value, 0.6);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(value, 0.5);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
    await tester.pumpAndSettle();
    expect(value, 0.6);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.pumpAndSettle();
    expect(value, 0.5);
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));

  testWidgets('Slider can be incremented and decremented by keyboard shortcuts - RTL', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Directionality(
                textDirection: TextDirection.rtl,
                child: Slider(
                  value: value,
                  onChanged: (double newValue) {
                    setState(() {
                      value = newValue;
                    });
                  },
                  autofocus: true,
                ),
              );
            }),
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(value, 0.45);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(value, 0.5);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
    await tester.pumpAndSettle();
    expect(value, 0.55);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.pumpAndSettle();
    expect(value, 0.5);
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android,  TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }));

  testWidgets('Slider can be incremented and decremented by keyboard shortcuts - RTL', (WidgetTester tester) async {
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double value = 0.5;
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Center(
            child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
              return Directionality(
                textDirection: TextDirection.rtl,
                child: Slider(
                  value: value,
                  onChanged: (double newValue) {
                    setState(() {
                      value = newValue;
                    });
                  },
                  autofocus: true,
                ),
              );
            }),
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(value, 0.4);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(value, 0.5);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
    await tester.pumpAndSettle();
    expect(value, 0.6);

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.pumpAndSettle();
    expect(value, 0.5);
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));

2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
  testWidgets('In directional nav, Slider can be navigated out of by using up and down arrows', (WidgetTester tester) async {
    const Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{
      SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
      SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
      SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
      SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
    };

    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    double topSliderValue = 0.5;
    double bottomSliderValue = 0.5;
    await tester.pumpWidget(
      MaterialApp(
        home: Shortcuts(
          shortcuts: shortcuts,
          child: Material(
            child: Center(
              child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
                return MediaQuery(
                  data: const MediaQueryData(navigationMode: NavigationMode.directional),
                  child: Column(
                    children: <Widget>[
                      Slider(
                        value: topSliderValue,
                        onChanged: (double newValue) {
                          setState(() {
                            topSliderValue = newValue;
                          });
                        },
                        autofocus: true,
                      ),
                      Slider(
                        value: bottomSliderValue,
                        onChanged: (double newValue) {
                          setState(() {
                            bottomSliderValue = newValue;
                          });
                        },
                      ),
                    ]
                  ),
                );
              }),
            ),
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();

    // The top slider is auto-focused and can be adjusted with left and right arrow keys.
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.55, reason: 'focused top Slider increased after first arrowRight');
    expect(bottomSliderValue, 0.5, reason: 'unfocused bottom Slider unaffected by first arrowRight');

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'focused top Slider decreased after first arrowLeft');
    expect(bottomSliderValue, 0.5, reason: 'unfocused bottom Slider unaffected by first arrowLeft');

    // Pressing the down-arrow key moves focus down to the bottom slider
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'arrowDown unfocuses top Slider, does not alter its value');
    expect(bottomSliderValue, 0.5, reason: 'arrowDown focuses bottom Slider, does not alter its value');

    // The bottom slider is now focused and can be adjusted with left and right arrow keys.
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'unfocused top Slider unaffected by second arrowRight');
    expect(bottomSliderValue, 0.55, reason: 'focused bottom Slider increased by second arrowRight');

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'unfocused top Slider unaffected by second arrowLeft');
    expect(bottomSliderValue, 0.5, reason: 'focused bottom Slider decreased by second arrowLeft');

    // Pressing the up-arrow key moves focus back up to the top slider
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'arrowUp focuses top Slider, does not alter its value');
    expect(bottomSliderValue, 0.5, reason: 'arrowUp unfocuses bottom Slider, does not alter its value');

    // The top slider is now focused again and can be adjusted with left and right arrow keys.
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.55, reason: 'focused top Slider increased after third arrowRight');
    expect(bottomSliderValue, 0.5, reason: 'unfocused bottom Slider unaffected by third arrowRight');

    await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
    await tester.pumpAndSettle();
    expect(topSliderValue, 0.5, reason: 'focused top Slider decreased after third arrowRight');
    expect(bottomSliderValue, 0.5, reason: 'unfocused bottom Slider unaffected by third arrowRight');
  });

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
  testWidgets('Slider gains keyboard focus when it gains semantics focus on Windows', (WidgetTester tester) async {
    final SemanticsTester semantics = SemanticsTester(tester);
    final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!;
    final FocusNode focusNode = FocusNode();
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Slider(
            value: 0.5,
            onChanged: (double _) {},
            focusNode: focusNode,
          ),
        ),
      ),
    );

    expect(semantics, hasSemantics(
      TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics(
            id: 1,
            textDirection: TextDirection.ltr,
            children: <TestSemantics>[
              TestSemantics(
                id: 2,
                children: <TestSemantics>[
                  TestSemantics(
                    id: 3,
                    flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
                    children: <TestSemantics>[
                      TestSemantics(
                        id: 4,
                        flags: <SemanticsFlag>[
                          SemanticsFlag.hasEnabledState,
                          SemanticsFlag.isEnabled,
                          SemanticsFlag.isFocusable,
                          SemanticsFlag.isSlider,
                        ],
                        actions: <SemanticsAction>[
                          SemanticsAction.increase,
                          SemanticsAction.decrease,
                          SemanticsAction.didGainAccessibilityFocus,
                        ],
                        value: '50%',
                        increasedValue: '55%',
                        decreasedValue: '45%',
                        textDirection: TextDirection.ltr,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
      ignoreRect: true,
      ignoreTransform: true,
    ));

    expect(focusNode.hasFocus, isFalse);
    semanticsOwner.performAction(4, SemanticsAction.didGainAccessibilityFocus);
    await tester.pumpAndSettle();
    expect(focusNode.hasFocus, isTrue);
    semantics.dispose();
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }));

2321
  testWidgets('Value indicator appears when it should', (WidgetTester tester) async {
2322
    final ThemeData baseTheme = ThemeData(
2323 2324 2325 2326 2327
      platform: TargetPlatform.android,
      primarySwatch: Colors.blue,
    );
    SliderThemeData theme = baseTheme.sliderTheme;
    double value = 0.45;
2328 2329
    Widget buildApp({ required SliderThemeData sliderTheme, int? divisions, bool enabled = true }) {
      final ValueChanged<double>? onChanged = enabled ? (double d) => value = d : null;
2330 2331 2332
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
          child: Material(
            child: Center(
              child: Theme(
                data: baseTheme,
                child: SliderTheme(
                  data: sliderTheme,
                  child: Slider(
                    value: value,
                    label: '$value',
                    divisions: divisions,
                    onChanged: onChanged,
2344
                  ),
2345 2346 2347 2348 2349 2350 2351 2352
                ),
              ),
            ),
          ),
        ),
      );
    }

2353
    Future<void> expectValueIndicator({
2354 2355 2356
      required bool isVisible,
      required SliderThemeData theme,
      int? divisions,
2357
      bool enabled = true,
2358 2359
    }) async {
      // Discrete enabled widget.
2360 2361 2362
      await tester.pumpWidget(buildApp(sliderTheme: theme, divisions: divisions, enabled: enabled));
      final Offset center = tester.getCenter(find.byType(Slider));
      final TestGesture gesture = await tester.startGesture(center);
2363
      // Wait for value indicator animation to finish.
2364
      await tester.pumpAndSettle();
2365

2366

2367
      final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
2368
      expect(
2369
        valueIndicatorBox,
2370
        isVisible
2371 2372
            ? (paints..path(color: theme.valueIndicatorColor)..paragraph())
            : isNot(paints..path(color: theme.valueIndicatorColor)..paragraph()),
2373 2374 2375 2376 2377
      );
      await gesture.up();
    }

    // Default (showValueIndicator set to onlyForDiscrete).
2378
    await expectValueIndicator(isVisible: true, theme: theme, divisions: 3);
2379
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3, enabled: false);
2380
    await expectValueIndicator(isVisible: false, theme: theme);
2381 2382 2383 2384
    await expectValueIndicator(isVisible: false, theme: theme, enabled: false);

    // With showValueIndicator set to onlyForContinuous.
    theme = theme.copyWith(showValueIndicator: ShowValueIndicator.onlyForContinuous);
2385
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3);
2386
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3, enabled: false);
2387
    await expectValueIndicator(isVisible: true, theme: theme);
2388 2389 2390 2391
    await expectValueIndicator(isVisible: false, theme: theme, enabled: false);

    // discrete enabled widget with showValueIndicator set to always.
    theme = theme.copyWith(showValueIndicator: ShowValueIndicator.always);
2392
    await expectValueIndicator(isVisible: true, theme: theme, divisions: 3);
2393
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3, enabled: false);
2394
    await expectValueIndicator(isVisible: true, theme: theme);
2395 2396 2397 2398
    await expectValueIndicator(isVisible: false, theme: theme, enabled: false);

    // discrete enabled widget with showValueIndicator set to never.
    theme = theme.copyWith(showValueIndicator: ShowValueIndicator.never);
2399
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3);
2400
    await expectValueIndicator(isVisible: false, theme: theme, divisions: 3, enabled: false);
2401
    await expectValueIndicator(isVisible: false, theme: theme);
2402 2403
    await expectValueIndicator(isVisible: false, theme: theme, enabled: false);
  });
2404 2405

  testWidgets("Slider doesn't start any animations after dispose", (WidgetTester tester) async {
2406
    final Key sliderKey = UniqueKey();
2407 2408
    double value = 0.0;
    await tester.pumpWidget(
2409 2410 2411 2412 2413
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
nt4f04uNd's avatar
nt4f04uNd committed
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
              return Material(
                child: Center(
                  child: Slider(
                    key: sliderKey,
                    value: value,
                    divisions: 4,
                    onChanged: (double newValue) {
                      setState(() {
                        value = newValue;
                      });
                    },
2425 2426
                  ),
                ),
2427 2428 2429
              );
            },
          ),
2430 2431 2432 2433 2434
        ),
      ),
    );

    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
2435
    await tester.pumpAndSettle();
2436 2437
    expect(value, equals(0.5));
    await gesture.moveBy(const Offset(-500.0, 0.0));
2438
    await tester.pumpAndSettle();
2439
    // Change the tree to dispose the original widget.
2440
    await tester.pumpWidget(Container());
2441
    expect(await tester.pumpAndSettle(), equals(1));
2442 2443
    await gesture.up();
  });
2444

2445 2446
  testWidgets('Slider removes value indicator from overlay if Slider gets disposed without value indicator animation completing.', (WidgetTester tester) async {
    final Key sliderKey = UniqueKey();
2447
    const Color fillColor = Color(0xf55f5f5f);
2448 2449 2450
    double value = 0.0;

    Widget buildApp({
2451
      int? divisions,
2452 2453 2454
      bool enabled = true,
    }) {
      return MaterialApp(
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
        home: Scaffold(
          body: Builder(
            // The builder is used to pass the context from the MaterialApp widget
            // to the [Navigator]. This context is required in order for the
            // Navigator to work.
            builder: (BuildContext context) {
              return Column(
                children: <Widget>[
                  Slider(
                    key: sliderKey,
                    max: 100.0,
                    divisions: divisions,
                    label: '${value.round()}',
                    value: value,
                    onChanged: (double newValue) {
                      value = newValue;
                    },
                  ),
2473
                  ElevatedButton(
2474 2475
                    child: const Text('Next'),
                    onPressed: () {
2476
                      Navigator.of(context).pushReplacement(
2477 2478
                        MaterialPageRoute<void>(
                          builder: (BuildContext context) {
2479
                            return ElevatedButton(
2480
                              child: const Text('Inner page'),
2481
                              onPressed: () { Navigator.of(context).pop(); },
2482 2483 2484 2485 2486 2487 2488 2489 2490
                            );
                          },
                        ),
                      );
                    },
                  ),
                ],
              );
            },
2491 2492 2493 2494 2495 2496 2497
          ),
        ),
      );
    }

    await tester.pumpWidget(buildApp(divisions: 3));

2498
    final RenderObject valueIndicatorBox = tester.renderObject(find.byType(Overlay));
2499 2500 2501 2502 2503 2504 2505 2506 2507
    final Offset topRight = tester.getTopRight(find.byType(Slider)).translate(-24, 0);
    final TestGesture gesture = await tester.startGesture(topRight);
    // Wait for value indicator animation to finish.
    await tester.pumpAndSettle();

    expect(find.byType(Slider), isNotNull);
    expect(
      valueIndicatorBox,
      paints
2508 2509 2510 2511 2512
        // Represents the raised button with text, next.
        ..path(color: Colors.black)
        ..paragraph()
        // Represents the Slider.
        ..path(color: fillColor)
2513
        ..paragraph(),
2514 2515
    );

2516
    expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 3));
2517 2518
    expect(valueIndicatorBox, paintsExactlyCountTimes(#drawParagraph, 2));

2519 2520 2521 2522 2523 2524 2525
    await tester.tap(find.text('Next'));
    await tester.pumpAndSettle();

    expect(find.byType(Slider), findsNothing);
    expect(
      valueIndicatorBox,
      isNot(
2526 2527 2528
        paints
          ..path(color: fillColor)
          ..paragraph(),
2529 2530 2531
      ),
    );

2532
    // Represents the ElevatedButton with inner Text, inner page.
2533
    expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 2));
2534 2535
    expect(valueIndicatorBox, paintsExactlyCountTimes(#drawParagraph, 1));

2536 2537 2538 2539 2540
    // Don't stop holding the value indicator.
    await gesture.up();
    await tester.pumpAndSettle();
  });

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
  testWidgets('Slider.adaptive', (WidgetTester tester) async {
    double value = 0.5;

    Widget buildFrame(TargetPlatform platform) {
      return MaterialApp(
        theme: ThemeData(platform: platform),
        home: StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return Material(
              child: Center(
                child: Slider.adaptive(
                  value: value,
                  onChanged: (double newValue) {
                    setState(() {
                      value = newValue;
                    });
                  },
                ),
              ),
            );
          },
        ),
      );
    }

Dan Field's avatar
Dan Field committed
2566 2567 2568 2569 2570 2571
    for (final TargetPlatform platform in <TargetPlatform>[TargetPlatform.iOS, TargetPlatform.macOS]) {
      value = 0.5;
      await tester.pumpWidget(buildFrame(platform));
      expect(find.byType(Slider), findsOneWidget);
      expect(find.byType(CupertinoSlider), findsOneWidget);

2572
      expect(value, 0.5, reason: 'on ${platform.name}');
Dan Field's avatar
Dan Field committed
2573 2574 2575
      final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CupertinoSlider)));
      // Drag to the right end of the track.
      await gesture.moveBy(const Offset(600.0, 0.0));
2576
      expect(value, 1.0, reason: 'on ${platform.name}');
Dan Field's avatar
Dan Field committed
2577 2578 2579
      await gesture.up();
    }

2580
    for (final TargetPlatform platform in <TargetPlatform>[TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows]) {
Dan Field's avatar
Dan Field committed
2581 2582 2583 2584 2585 2586
      value = 0.5;
      await tester.pumpWidget(buildFrame(platform));
      await tester.pumpAndSettle(); // Finish the theme change animation.
      expect(find.byType(Slider), findsOneWidget);
      expect(find.byType(CupertinoSlider), findsNothing);

2587
      expect(value, 0.5, reason: 'on ${platform.name}');
Dan Field's avatar
Dan Field committed
2588 2589 2590
      final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Slider)));
      // Drag to the right end of the track.
      await gesture.moveBy(const Offset(600.0, 0.0));
2591
      expect(value, 1.0, reason: 'on ${platform.name}');
Dan Field's avatar
Dan Field committed
2592 2593
      await gesture.up();
    }
2594
  });
2595 2596 2597 2598 2599

  testWidgets('Slider respects height from theme', (WidgetTester tester) async {
    final Key sliderKey = UniqueKey();
    double value = 0.0;
    await tester.pumpWidget(
2600 2601 2602 2603 2604 2605
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              final SliderThemeData sliderTheme = SliderTheme.of(context).copyWith(tickMarkShape: TallSliderTickMarkShape());
nt4f04uNd's avatar
nt4f04uNd committed
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
              return Material(
                child: Center(
                  child: IntrinsicHeight(
                    child: SliderTheme(
                      data: sliderTheme,
                      child: Slider(
                        key: sliderKey,
                        value: value,
                        divisions: 4,
                        onChanged: (double newValue) {
                          setState(() {
                            value = newValue;
                          });
                        },
2620 2621 2622 2623
                      ),
                    ),
                  ),
                ),
2624 2625 2626
              );
            },
          ),
2627 2628 2629 2630 2631 2632 2633
        ),
      ),
    );

    final RenderBox renderObject = tester.renderObject<RenderBox>(find.byType(Slider));
    expect(renderObject.size.height, 200);
  });
2634

2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
  testWidgets('Slider changes mouse cursor when hovered', (WidgetTester tester) async {
    // Test Slider() constructor
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Slider(
                  mouseCursor: SystemMouseCursors.text,
                  value: 0.5,
                  onChanged: (double newValue) { },
                ),
              ),
            ),
          ),
        ),
2654
      ),
2655 2656 2657 2658 2659 2660 2661 2662
    );

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

    await tester.pump();

2663
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682

    // Test Slider.adaptive() constructor
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Slider.adaptive(
                  mouseCursor: SystemMouseCursors.text,
                  value: 0.5,
                  onChanged: (double newValue) { },
                ),
              ),
            ),
          ),
        ),
2683
      ),
2684 2685
    );

2686
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704

    // Test default cursor
    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Slider(
                  value: 0.5,
                  onChanged: (double newValue) { },
                ),
              ),
            ),
          ),
        ),
2705
      ),
2706 2707
    );

2708
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
2709 2710
  });

2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
  testWidgets('Slider MaterialStateMouseCursor resolves correctly', (WidgetTester tester) async {
    const MouseCursor disabledCursor = SystemMouseCursors.basic;
    const MouseCursor hoveredCursor = SystemMouseCursors.grab;
    const MouseCursor draggedCursor = SystemMouseCursors.move;

    Widget buildFrame({ required bool enabled }) {
      return MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: MouseRegion(
                cursor: SystemMouseCursors.forbidden,
                child: Slider(
                  mouseCursor: const _StateDependentMouseCursor(
                    disabled: disabledCursor,
                    hovered: hoveredCursor,
                    dragged: draggedCursor,
                  ),
                  value: 0.5,
                  onChanged: enabled ? (double newValue) { } : null,
                ),
              ),
            ),
          ),
        ),
      );
    }

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

    await tester.pumpWidget(buildFrame(enabled: false));
2745
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), disabledCursor);
2746 2747

    await tester.pumpWidget(buildFrame(enabled: true));
2748
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
2749 2750 2751

    await gesture.moveTo(tester.getCenter(find.byType(Slider))); // start hover
    await tester.pumpAndSettle();
2752
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), hoveredCursor);
2753 2754 2755 2756 2757 2758

    await tester.timedDrag(
      find.byType(Slider),
      const Offset(20.0, 0.0),
      const Duration(milliseconds: 100),
    );
2759
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.move);
2760 2761
  });

2762
  testWidgets('Slider implements debugFillProperties', (WidgetTester tester) async {
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();

    const Slider(
      activeColor: Colors.blue,
      divisions: 10,
      inactiveColor: Colors.grey,
      label: 'Set a value',
      max: 100.0,
      onChanged: null,
      value: 50.0,
    ).debugFillProperties(builder);

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

    expect(description, <String>[
      'value: 50.0',
      'disabled',
      'min: 0.0',
      'max: 100.0',
      'divisions: 10',
      'label: "Set a value"',
      'activeColor: MaterialColor(primary value: Color(0xff2196f3))',
      'inactiveColor: MaterialColor(primary value: Color(0xff9e9e9e))',
    ]);
  });
2790

2791
  testWidgets('Slider track paints correctly when the shape is rectangular', (WidgetTester tester) async {
2792 2793 2794
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
2795 2796 2797
          sliderTheme: const SliderThemeData(
            trackShape: RectangularSliderTrackShape(),
          ),
2798
        ),
nt4f04uNd's avatar
nt4f04uNd committed
2799
        home: const Directionality(
2800
          textDirection: TextDirection.ltr,
nt4f04uNd's avatar
nt4f04uNd committed
2801 2802 2803 2804 2805
          child: Material(
            child: Center(
              child: Slider(
                value: 0.5,
                onChanged: null,
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
              ),
            ),
          ),
        ),
      ),
    );

    // _RenderSlider is the last render object in the tree.
    final RenderObject renderObject = tester.allRenderObjects.last;

    // The active track rect should start at 24.0 pixels,
    // and there should not have a gap between active and inactive track.
2818 2819 2820 2821 2822
    expect(
      renderObject,
      paints
        ..rect(rect: const Rect.fromLTRB(24.0, 298.0, 400.0, 302.0)) // active track Rect.
        ..rect(rect: const Rect.fromLTRB(400.0, 298.0, 776.0, 302.0)), // inactive track Rect.
2823 2824
    );
  });
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849

  testWidgets('Slider can be painted in a narrower constraint', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: Material(
            child: Center(
              child: SizedBox(
                height: 10.0,
                width: 10.0,
                child: Slider(
                  value: 0.5,
                  onChanged: null,
                ),
              ),
            ),
          ),
        ),
      ),
    );

    // _RenderSlider is the last render object in the tree.
    final RenderObject renderObject = tester.allRenderObjects.last;

2850 2851 2852 2853 2854 2855 2856 2857 2858
    expect(
      renderObject,
      paints
        // active track RRect
        ..rrect(rrect: RRect.fromLTRBAndCorners(-14.0, 2.0, 5.0, 8.0, topLeft: const Radius.circular(3.0), bottomLeft: const Radius.circular(3.0)))
        // inactive track RRect
        ..rrect(rrect: RRect.fromLTRBAndCorners(5.0, 3.0, 24.0, 7.0, topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0)))
        // thumb
        ..circle(x: 5.0, y: 5.0, radius: 10.0, ),
2859 2860
    );
  });
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887

  testWidgets('Update the divisions and value at the same time for Slider', (WidgetTester tester) async {
    // Regress test for https://github.com/flutter/flutter/issues/65943
    Widget buildFrame(double maxValue) {
      return MaterialApp(
        home: Material(
          child: Center(
            child: Slider.adaptive(
              value: 5,
              max: maxValue,
              divisions: maxValue.toInt(),
              onChanged: (double newValue) {},
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame(10));

    // _RenderSlider is the last render object in the tree.
    final RenderObject renderObject = tester.allRenderObjects.last;

    // Update the divisions from 10 to 15, the thumb should be paint at the correct position.
    await tester.pumpWidget(buildFrame(15));
    await tester.pumpAndSettle(); // Finish the animation.

2888
    late RRect activeTrackRRect;
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
    expect(renderObject, paints..something((Symbol method, List<dynamic> arguments) {
      if (method != #drawRRect)
        return false;
      activeTrackRRect = arguments[0] as RRect;
      return true;
    }));

    // The thumb should at one-third(5 / 15) of the Slider.
    // The right of the active track shape is the position of the thumb.
    // 24.0 is the default margin, (800.0 - 24.0 - 24.0) is the slider's width.
    expect(nearEqual(activeTrackRRect.right, (800.0 - 24.0 - 24.0) * (5 / 15) + 24.0, 0.01), true);
  });
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001


  testWidgets('Slider paints thumbColor', (WidgetTester tester) async {
    const Color color = Color(0xffffc107);

    final Widget sliderAdaptive = MaterialApp(
      theme: ThemeData(platform: TargetPlatform.iOS),
      home: Material(
        child: Slider(
          value: 0,
          onChanged: (double newValue) {},
          thumbColor: color,
        ),
      ),
    );

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

    final MaterialInkController material =
        Material.of(tester.element(find.byType(Slider)))!;
    expect(material, paints..circle(color: color));
  });

  testWidgets('Slider.adaptive paints thumbColor on Android',
      (WidgetTester tester) async {
    const Color color = Color(0xffffc107);

    final Widget sliderAdaptive = MaterialApp(
      theme: ThemeData(platform: TargetPlatform.android),
      home: Material(
        child: Slider.adaptive(
          value: 0,
          onChanged: (double newValue) {},
          thumbColor: color,
        ),
      ),
    );

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

    final MaterialInkController material =
        Material.of(tester.element(find.byType(Slider)))!;
    expect(material, paints..circle(color: color));
  });

  testWidgets('If thumbColor is null, it defaults to CupertinoColors.white',
      (WidgetTester tester) async {
    final Widget sliderAdaptive = MaterialApp(
      theme: ThemeData(platform: TargetPlatform.iOS),
      home: Material(
        child: Slider.adaptive(
          value: 0,
          onChanged: (double newValue) {},
        ),
      ),
    );

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

    final MaterialInkController material =
        Material.of(tester.element(find.byType(CupertinoSlider)))!;
    expect(
      material,
      paints
        ..rrect()
        ..rrect()
        ..rrect()
        ..rrect()
        ..rrect()
        ..rrect(color: CupertinoColors.white),
    );
  });

  testWidgets('Slider.adaptive passes thumbColor to CupertinoSlider',
      (WidgetTester tester) async {
    const Color color = Color(0xffffc107);

    final Widget sliderAdaptive = MaterialApp(
      theme: ThemeData(platform: TargetPlatform.iOS),
      home: Material(
        child: Slider.adaptive(
          value: 0,
          onChanged: (double newValue) {},
          thumbColor: color,
        ),
      ),
    );

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

    final MaterialInkController material =
        Material.of(tester.element(find.byType(CupertinoSlider)))!;
    expect(
      material,
      paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: color),
    );
  });
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108

  // Regression test for https://github.com/flutter/flutter/issues/103566
  testWidgets('Drag gesture uses provided gesture settings', (WidgetTester tester) async {
    double value = 0.5;
    bool dragStarted = false;
    final Key sliderKey = UniqueKey();

    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Material(
                child: Center(
                  child: GestureDetector(
                    behavior: HitTestBehavior.deferToChild,
                    onHorizontalDragStart: (DragStartDetails details) {
                      dragStarted = true;
                    },
                    child: MediaQuery(
                      data: MediaQuery.of(context).copyWith(gestureSettings: const DeviceGestureSettings(touchSlop: 20)),
                      child: Slider(
                        value: value,
                        key: sliderKey,
                        onChanged: (double newValue) {
                          setState(() {
                            value = newValue;
                          });
                        },
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );

    TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
    await tester.pump(kPressTimeout);

    // Less than configured touch slop, more than default touch slop
    await drag.moveBy(const Offset(19.0, 0));
    await tester.pump();

    expect(value, 0.5);
    expect(dragStarted, true);

    dragStarted = false;

    await drag.up();
    await tester.pumpAndSettle();

    drag = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
    await tester.pump(kPressTimeout);

    bool sliderEnd = false;

    await tester.pumpWidget(
      MaterialApp(
        home: Directionality(
          textDirection: TextDirection.ltr,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Material(
                child: Center(
                  child: GestureDetector(
                    behavior: HitTestBehavior.deferToChild,
                    onHorizontalDragStart: (DragStartDetails details) {
                      dragStarted = true;
                    },
                    child: MediaQuery(
                      data: MediaQuery.of(context).copyWith(gestureSettings: const DeviceGestureSettings(touchSlop: 10)),
                      child: Slider(
                        value: value,
                        key: sliderKey,
                        onChanged: (double newValue) {
                          setState(() {
                            value = newValue;
                          });
                        },
                        onChangeEnd: (double endValue) {
                          sliderEnd = true;
                        },
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );

    // More than touch slop.
    await drag.moveBy(const Offset(12.0, 0));

    await drag.up();
    await tester.pumpAndSettle();

    expect(sliderEnd, true);
    expect(dragStarted, false);
  });
3109
}