sliding_segmented_control.dart 36.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';

import 'colors.dart';

// Extracted from https://developer.apple.com/design/resources/.

// Minimum padding from edges of the segmented control to edges of
// encompassing widget.
const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(vertical: 2, horizontal: 3);

// The corner radius of the thumb.
const Radius _kThumbRadius = Radius.circular(6.93);
// The amount of space by which to expand the thumb from the size of the currently
// selected child.
const EdgeInsets _kThumbInsets = EdgeInsets.symmetric(horizontal: 1);

// Minimum height of the segmented control.
const double _kMinSegmentedControlHeight = 28.0;

const Color _kSeparatorColor = Color(0x4D8E8E93);

const CupertinoDynamicColor _kThumbColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xFFFFFFFF),
  darkColor: Color(0xFF636366),
);

// The amount of space by which to inset each separator.
const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 6);
const double _kSeparatorWidth = 1;
const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth/2);

// The minimum scale factor of the thumb, when being pressed on for a sufficient
// amount of time.
const double _kMinThumbScale = 0.95;

// The minimum horizontal distance between the edges of the separator and the
// closest child.
const double _kSegmentMinPadding = 9.25;

// The threshold value used in hasDraggedTooFar, for checking against the square
// L2 distance from the location of the current drag pointer, to the closest
52
// vertex of the CupertinoSlidingSegmentedControl's Rect.
53 54 55 56 57 58 59 60 61 62 63 64 65 66
//
// Both the mechanism and the value are speculated.
const double _kTouchYDistanceThreshold = 50.0 * 50.0;

// The corner radius of the segmented control.
//
// Inspected from iOS 13.2 simulator.
const double _kCornerRadius = 8;

// The spring animation used when the thumb changes its rect.
final SpringSimulation _kThumbSpringAnimationSimulation = SpringSimulation(
  const SpringDescription(mass: 1, stiffness: 503.551, damping: 44.8799),
  0,
  1,
67
  0, // Every time a new spring animation starts the previous animation stops.
68 69 70 71 72 73 74 75 76
);

const Duration _kSpringAnimationDuration = Duration(milliseconds: 412);

const Duration _kOpacityAnimationDuration = Duration(milliseconds: 470);

const Duration _kHighlightAnimationDuration = Duration(milliseconds: 200);

class _FontWeightTween extends Tween<FontWeight> {
77
  _FontWeightTween({ required FontWeight begin, required FontWeight end }) : super(begin: begin, end: end);
78 79

  @override
80
  FontWeight lerp(double t) => FontWeight.lerp(begin, end, t)!;
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
}

/// An iOS 13 style segmented control.
///
/// Displays the widgets provided in the [Map] of [children] in a horizontal list.
/// Used to select between a number of mutually exclusive options. When one option
/// in the segmented control is selected, the other options in the segmented
/// control cease to be selected.
///
/// A segmented control can feature any [Widget] as one of the values in its
/// [Map] of [children]. The type T is the type of the [Map] keys used to identify
/// each widget and determine which widget is selected. As required by the [Map]
/// class, keys must be of consistent types and must be comparable. The [children]
/// argument must be an ordered [Map] such as a [LinkedHashMap], the ordering of
/// the keys will determine the order of the widgets in the segmented control.
///
97 98 99 100 101 102
/// When the state of the segmented control changes, the widget calls the
/// [onValueChanged] callback. The map key associated with the newly selected
/// widget is returned in the [onValueChanged] callback. Typically, widgets
/// that use a segmented control will listen for the [onValueChanged] callback
/// and rebuild the segmented control with a new [groupValue] to update which
/// option is currently selected.
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
///
/// The [children] will be displayed in the order of the keys in the [Map].
/// The height of the segmented control is determined by the height of the
/// tallest widget provided as a value in the [Map] of [children].
/// The width of each child in the segmented control will be equal to the width
/// of widest child, unless the combined width of the children is wider than
/// the available horizontal space. In this case, the available horizontal space
/// is divided by the number of provided [children] to determine the width of
/// each widget. The selection area for each of the widgets in the [Map] of
/// [children] will then be expanded to fill the calculated space, so each
/// widget will appear to have the same dimensions.
///
/// A segmented control may optionally be created with custom colors. The
/// [thumbColor], [backgroundColor] arguments can be used to override the segmented
/// control's colors from its defaults.
///
/// See also:
///
Dan Field's avatar
Dan Field committed
121 122
///  * [CupertinoSlidingSegmentedControl], a segmented control widget in the
///    style introduced in iOS 13.
123 124 125 126
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/segmented-controls/>
class CupertinoSlidingSegmentedControl<T> extends StatefulWidget {
  /// Creates an iOS-style segmented control bar.
  ///
127 128 129
  /// The [children] and [onValueChanged] arguments must not be null. The
  /// [children] argument must be an ordered [Map] such as a [LinkedHashMap].
  /// Further, the length of the [children] list must be greater than one.
130
  ///
131 132 133 134
  /// Each widget value in the map of [children] must have an associated key
  /// that uniquely identifies this widget. This key is what will be returned
  /// in the [onValueChanged] callback when a new value from the [children] map
  /// is selected.
135
  ///
136 137 138 139
  /// The [groupValue] is the currently selected value for the segmented control.
  /// If no [groupValue] is provided, or the [groupValue] is null, no widget will
  /// appear as selected. The [groupValue] must be either null or one of the keys
  /// in the [children] map.
140
  CupertinoSlidingSegmentedControl({
141 142 143
    Key? key,
    required this.children,
    required this.onValueChanged,
144
    this.groupValue,
145 146 147 148 149 150
    this.thumbColor = _kThumbColor,
    this.padding = _kHorizontalItemPadding,
    this.backgroundColor = CupertinoColors.tertiarySystemFill,
  }) : assert(children != null),
       assert(children.length >= 2),
       assert(padding != null),
151
       assert(onValueChanged != null),
152
       assert(
153 154
         groupValue == null || children.keys.contains(groupValue),
         'The groupValue must be either null or one of the keys in the children map.',
155 156 157 158 159 160 161 162 163 164
       ),
       super(key: key);

  /// The identifying keys and corresponding widget values in the
  /// segmented control.
  ///
  /// The map must have more than one entry.
  /// This attribute must be an ordered [Map] such as a [LinkedHashMap].
  final Map<T, Widget> children;

165 166 167 168
  /// The identifier of the widget that is currently selected.
  ///
  /// This must be one of the keys in the [Map] of [children].
  /// If this attribute is null, no widget will be initially selected.
169
  final T? groupValue;
170 171 172 173 174 175 176 177 178 179 180 181

  /// The callback that is called when a new option is tapped.
  ///
  /// This attribute must not be null.
  ///
  /// The segmented control passes the newly selected widget's associated key
  /// to the callback but does not actually change state until the parent
  /// widget rebuilds the segmented control with the new [groupValue].
  ///
  /// The callback provided to [onValueChanged] should update the state of
  /// the parent [StatefulWidget] using the [State.setState] method, so that
  /// the parent gets rebuilt; for example:
182
  ///
183
  /// {@tool snippet}
184
  ///
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  /// ```dart
  /// class SegmentedControlExample extends StatefulWidget {
  ///   @override
  ///   State createState() => SegmentedControlExampleState();
  /// }
  ///
  /// class SegmentedControlExampleState extends State<SegmentedControlExample> {
  ///   final Map<int, Widget> children = const {
  ///     0: Text('Child 1'),
  ///     1: Text('Child 2'),
  ///   };
  ///
  ///   int currentValue;
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return Container(
  ///       child: CupertinoSlidingSegmentedControl<int>(
  ///         children: children,
  ///         onValueChanged: (int newValue) {
  ///           setState(() {
  ///             currentValue = newValue;
  ///           });
  ///         },
  ///         groupValue: currentValue,
  ///       ),
  ///     );
  ///   }
  /// }
  /// ```
  /// {@end-tool}
216
  final ValueChanged<T?> onValueChanged;
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

  /// The color used to paint the rounded rect behind the [children] and the separators.
  ///
  /// The default value is [CupertinoColors.tertiarySystemFill]. The background
  /// will not be painted if null is specified.
  final Color backgroundColor;

  /// The color used to paint the interior of the thumb that appears behind the
  /// currently selected item.
  ///
  /// The default value is a [CupertinoDynamicColor] that appears white in light
  /// mode and becomes a gray color in dark mode.
  final Color thumbColor;

  /// The amount of space by which to inset the [children].
  ///
  /// Must not be null. Defaults to EdgeInsets.symmetric(vertical: 2, horizontal: 3).
  final EdgeInsetsGeometry padding;

  @override
  _SegmentedControlState<T> createState() => _SegmentedControlState<T>();
}

class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T>>
    with TickerProviderStateMixin<CupertinoSlidingSegmentedControl<T>> {

  final Map<T, AnimationController> _highlightControllers = <T, AnimationController>{};
244
  final Tween<FontWeight> _highlightTween = _FontWeightTween(begin: FontWeight.normal, end: FontWeight.w500);
245 246 247 248

  final Map<T, AnimationController> _pressControllers = <T, AnimationController>{};
  final Tween<double> _pressTween = Tween<double>(begin: 1, end: 0.2);

249
  late List<T> keys;
250

251 252 253
  late AnimationController thumbController;
  late AnimationController separatorOpacityController;
  late AnimationController thumbScaleController;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

  final TapGestureRecognizer tap = TapGestureRecognizer();
  final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer();
  final LongPressGestureRecognizer longPress = LongPressGestureRecognizer();

  AnimationController _createHighlightAnimationController({ bool isCompleted = false }) {
    return AnimationController(
      duration: _kHighlightAnimationDuration,
      value: isCompleted ? 1 : 0,
      vsync: this,
    );
  }

  AnimationController _createFadeoutAnimationController() {
    return AnimationController(
      duration: _kOpacityAnimationDuration,
      vsync: this,
    );
  }

  @override
  void initState() {
    super.initState();

    final GestureArenaTeam team = GestureArenaTeam();
    // If the long press or horizontal drag recognizer gets accepted, we know for
    // sure the gesture is meant for the segmented control. Hand everything to
    // the drag gesture recognizer.
    longPress.team = team;
    drag.team = team;
    team.captain = drag;

286
    _highlighted = widget.groupValue;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

    thumbController = AnimationController(
      duration: _kSpringAnimationDuration,
      value: 0,
      vsync: this,
    );

    thumbScaleController = AnimationController(
      duration: _kSpringAnimationDuration,
      value: 1,
      vsync: this,
    );

    separatorOpacityController = AnimationController(
      duration: _kSpringAnimationDuration,
      value: 0,
      vsync: this,
    );

306
    for (final T currentKey in widget.children.keys) {
307
      _highlightControllers[currentKey] = _createHighlightAnimationController(
308
        isCompleted: currentKey == widget.groupValue,  // Highlight the current selection.
309 310 311 312 313 314 315 316 317 318
      );
      _pressControllers[currentKey] = _createFadeoutAnimationController();
    }
  }

  @override
  void didUpdateWidget(CupertinoSlidingSegmentedControl<T> oldWidget) {
    super.didUpdateWidget(oldWidget);

    // Update animation controllers.
319
    for (final T oldKey in oldWidget.children.keys) {
320
      if (!widget.children.containsKey(oldKey)) {
321 322
        _highlightControllers[oldKey]!.dispose();
        _pressControllers[oldKey]!.dispose();
323 324 325 326 327 328

        _highlightControllers.remove(oldKey);
        _pressControllers.remove(oldKey);
      }
    }

329
    for (final T newKey in widget.children.keys) {
330 331 332 333 334 335
      if (!_highlightControllers.keys.contains(newKey)) {
        _highlightControllers[newKey] = _createHighlightAnimationController();
        _pressControllers[newKey] = _createFadeoutAnimationController();
      }
    }

336
    highlighted = widget.groupValue;
337 338 339 340
  }

  @override
  void dispose() {
341
    for (final AnimationController animationController in _highlightControllers.values) {
342 343 344
      animationController.dispose();
    }

345
    for (final AnimationController animationController in _pressControllers.values) {
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
      animationController.dispose();
    }

    thumbScaleController.dispose();
    thumbController.dispose();
    separatorOpacityController.dispose();

    drag.dispose();
    tap.dispose();
    longPress.dispose();

    super.dispose();
  }

  // Play highlight animation for the child located at _highlightControllers[at].
361
  void _animateHighlightController({ T? at, required bool forward }) {
362 363
    if (at == null)
      return;
364
    final AnimationController? controller = _highlightControllers[at];
365 366 367 368
    assert(!forward || controller != null);
    controller?.animateTo(forward ? 1 : 0, duration: _kHighlightAnimationDuration, curve: Curves.ease);
  }

369 370
  T? _highlighted;
  set highlighted(T? newValue) {
371 372 373 374 375 376 377
    if (_highlighted == newValue)
      return;
    _animateHighlightController(at: newValue, forward: true);
    _animateHighlightController(at: _highlighted, forward: false);
    _highlighted = newValue;
  }

378 379
  T? _pressed;
  set pressed(T? newValue) {
380 381 382 383 384 385 386
    if (_pressed == newValue)
      return;

    if (_pressed != null) {
      _pressControllers[_pressed]?.animateTo(0, duration: _kOpacityAnimationDuration, curve: Curves.ease);
    }
    if (newValue != _highlighted && newValue != null) {
387
      _pressControllers[newValue]!.animateTo(1, duration: _kOpacityAnimationDuration, curve: Curves.ease);
388 389 390 391 392
    }
    _pressed = newValue;
  }

  void didChangeSelectedViaGesture() {
393
    widget.onValueChanged(_highlighted);
394 395
  }

396
  T? indexToKey(int? index) => index == null ? null : keys[index];
397 398 399 400 401

  @override
  Widget build(BuildContext context) {
    debugCheckHasDirectionality(context);

402
    switch (Directionality.of(context)!) {
403 404 405 406 407 408 409 410 411 412 413 414 415
      case TextDirection.ltr:
        keys = widget.children.keys.toList(growable: false);
        break;
      case TextDirection.rtl:
        keys = widget.children.keys.toList().reversed.toList(growable: false);
        break;
    }

    return AnimatedBuilder(
      animation: Listenable.merge(<Listenable>[
        ..._highlightControllers.values,
        ..._pressControllers.values,
      ]),
416
      builder: (BuildContext context, Widget? child) {
417
        final List<Widget> children = <Widget>[];
418
        for (final T currentKey in keys) {
419
          final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith(
420
            fontWeight: _highlightTween.evaluate(_highlightControllers[currentKey]!),
421 422 423 424 425 426
          );

          final Widget child = DefaultTextStyle(
            style: textStyle,
            child: Semantics(
              button: true,
427
              onTap: () { widget.onValueChanged(currentKey); },
428
              inMutuallyExclusiveGroup: true,
429
              selected: widget.groupValue == currentKey,
430
              child: Opacity(
431
                opacity: _pressTween.evaluate(_pressControllers[currentKey]!),
432 433 434 435 436 437 438 439 440 441 442 443
                // Expand the hitTest area to be as large as the Opacity widget.
                child: MetaData(
                  behavior: HitTestBehavior.opaque,
                  child: Center(child: widget.children[currentKey]),
                ),
              ),
            ),
          );

          children.add(child);
        }

444
        final int? selectedIndex = widget.groupValue == null ? null : keys.indexOf(widget.groupValue as T);
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

        final Widget box = _SegmentedControlRenderWidget<T>(
          children: children,
          selectedIndex: selectedIndex,
          thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor, context),
          state: this,
        );

        return UnconstrainedBox(
          constrainedAxis: Axis.horizontal,
          child: Container(
            padding: widget.padding.resolve(Directionality.of(context)),
            decoration: BoxDecoration(
              borderRadius: const BorderRadius.all(Radius.circular(_kCornerRadius)),
              color: CupertinoDynamicColor.resolve(widget.backgroundColor, context),
            ),
            child: box,
          ),
        );
      },
    );
  }
}

class _SegmentedControlRenderWidget<T> extends MultiChildRenderObjectWidget {
  _SegmentedControlRenderWidget({
471
    Key? key,
472
    List<Widget> children = const <Widget>[],
473 474 475
    required this.selectedIndex,
    required this.thumbColor,
    required this.state,
476 477
  }) : super(key: key, children: children);

478 479
  final int? selectedIndex;
  final Color? thumbColor;
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  final _SegmentedControlState<T> state;

  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderSegmentedControl<T>(
      selectedIndex: selectedIndex,
      thumbColor: CupertinoDynamicColor.resolve(thumbColor, context),
      state: state,
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderSegmentedControl<T> renderObject) {
    renderObject
      ..thumbColor = CupertinoDynamicColor.resolve(thumbColor, context)
      ..guardedSetHighlightedIndex(selectedIndex);
  }
}

class _ChildAnimationManifest {
  _ChildAnimationManifest({
    this.opacity = 1,
502
    required this.separatorOpacity,
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
  }) : assert(separatorOpacity != null),
       assert(opacity != null),
       separatorTween = Tween<double>(begin: separatorOpacity, end: separatorOpacity),
       opacityTween = Tween<double>(begin: opacity, end: opacity);

  double opacity;
  Tween<double> opacityTween;
  double separatorOpacity;
  Tween<double> separatorTween;
}

class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData<RenderBox> { }

// The behavior of a UISegmentedControl as observed on iOS 13.1:
//
// 1. Tap up inside events will set the current selected index to the index of the
//    segment at the tap up location instantaneously (there might be animation but
//    the index change seems to happen before animation finishes), unless the tap
//    down event from the same touch event didn't happen within the segmented
//    control, in which case the touch event will be ignored entirely (will be
//    referring to these touch events as invalid touch events below).
//
// 2. A valid tap up event will also trigger the sliding CASpringAnimation (even
//    when it lands on the current segment), starting from the current `frame`
//    of the thumb. The previous sliding animation, if still playing, will be
//    removed and its velocity reset to 0. The sliding animation has a fixed
//    duration, regardless of the distance or transform.
//
// 3. When the sliding animation plays two other animations take place. In one animation
//    the content of the current segment gradually becomes "highlighted", turning the
//    font weight to semibold (CABasicAnimation, timingFunction = default, duration = 0.2).
//    The other is the separator fadein/fadeout animation.
//
// 4. A tap down event on the segment pointed to by the current selected
//    index will trigger a CABasicAnimation that shrinks the thumb to 95% of its
//    original size, even if the sliding animation is still playing. The
///   corresponding tap up event inverts the process (eyeballed).
//
// 5. A tap down event on other segments will trigger a CABasicAnimation
//    (timingFunction = default, duration = 0.47.) that fades out the content,
//    eventually reducing the alpha of that segment to 20% unless interrupted by
//    a tap up event or the pointer moves out of the region (either outside of the
//    segmented control's vicinity or to a different segment). The reverse animation
//    has the same duration and timing function.
class _RenderSegmentedControl<T> extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,
        RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {
  _RenderSegmentedControl({
551 552 553
    required int? selectedIndex,
    required Color? thumbColor,
    required this.state,
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  }) : _highlightedIndex = selectedIndex,
       _thumbColor = thumbColor,
       assert(state != null) {
         state.drag
          ..onDown = _onDown
          ..onUpdate = _onUpdate
          ..onEnd = _onEnd
          ..onCancel = _onCancel;

         state.tap.onTapUp = _onTapUp;
         // Empty callback to enable the long press recognizer.
         state.longPress.onLongPress = () { };
       }

  final _SegmentedControlState<T> state;

570
  Map<RenderBox, _ChildAnimationManifest>? _childAnimations = <RenderBox, _ChildAnimationManifest>{};
571 572

  // The current **Unscaled** Thumb Rect.
573
  Rect? currentThumbRect;
574

575
  Tween<Rect?>? _currentThumbTween;
576 577 578 579 580

  Tween<double> _thumbScaleTween = Tween<double>(begin: _kMinThumbScale, end: 1);
  double currentThumbScale = 1;

  // The current position of the active drag pointer.
581
  Offset? _localDragOffset;
582
  // Whether the current drag gesture started on a selected segment.
583
  bool? _startedOnSelectedSegment;
584 585

  @override
586
  void insert(RenderBox child, { RenderBox? after }) {
587 588 589 590
    super.insert(child, after: after);
    if (_childAnimations == null)
      return;

591 592
    assert(_childAnimations![child] == null);
    _childAnimations![child] = _ChildAnimationManifest(separatorOpacity: 1);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
  }

  @override
  void remove(RenderBox child) {
    super.remove(child);
    _childAnimations?.remove(child);
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    state.thumbController.addListener(markNeedsPaint);
    state.thumbScaleController.addListener(markNeedsPaint);
    state.separatorOpacityController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    state.thumbController.removeListener(markNeedsPaint);
    state.thumbScaleController.removeListener(markNeedsPaint);
    state.separatorOpacityController.removeListener(markNeedsPaint);
    super.detach();
  }

  // Indicates whether selectedIndex has changed and animations need to be updated.
  // when true some animation tweens will be updated in paint phase.
  bool _needsThumbAnimationUpdate = false;

621 622 623
  int? get highlightedIndex => _highlightedIndex;
  int? _highlightedIndex;
  set highlightedIndex(int? value) {
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    if (_highlightedIndex == value) {
      return;
    }

    _needsThumbAnimationUpdate = true;
    _highlightedIndex = value;

    state.thumbController.animateWith(_kThumbSpringAnimationSimulation);

    state.separatorOpacityController.reset();
    state.separatorOpacityController.animateTo(
      1,
      duration: _kSpringAnimationDuration,
      curve: Curves.ease,
    );

    state.highlighted = state.indexToKey(value);
    markNeedsPaint();
    markNeedsSemanticsUpdate();
  }

645
  void guardedSetHighlightedIndex(int? value) {
646 647 648 649 650 651
    // Ignore set highlightedIndex when the user is dragging the thumb around.
    if (_startedOnSelectedSegment == true)
      return;
    highlightedIndex = value;
  }

652 653 654
  int? get pressedIndex => _pressedIndex;
  int? _pressedIndex;
  set pressedIndex(int? value) {
655 656 657 658 659 660 661 662 663 664
    if (_pressedIndex == value) {
      return;
    }

    assert(value == null || (value >= 0 && value < childCount));

    _pressedIndex = value;
    state.pressed = state.indexToKey(value);
  }

665 666 667
  Color? get thumbColor => _thumbColor;
  Color? _thumbColor;
  set thumbColor(Color? value) {
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    if (_thumbColor == value) {
      return;
    }
    _thumbColor = value;
    markNeedsPaint();
  }

  double get totalSeparatorWidth => (_kSeparatorInset.horizontal + _kSeparatorWidth) * (childCount - 1);

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent) {
      state.tap.addPointer(event);
      state.longPress.addPointer(event);
      state.drag.addPointer(event);
    }
  }

687
  int? indexFromLocation(Offset location) {
688 689 690
    return childCount == 0
      ? null
      // This assumes all children have the same width.
691 692 693
      : (location.dx / (size.width / childCount))
          .floor()
          .clamp(0, childCount - 1);
694 695 696 697 698 699 700 701 702 703
  }

  void _onTapUp(TapUpDetails details) {
    highlightedIndex = indexFromLocation(details.localPosition);
    state.didChangeSelectedViaGesture();
  }

  void _onDown(DragDownDetails details) {
    assert(size.contains(details.localPosition));
    _localDragOffset = details.localPosition;
704
    final int? index = indexFromLocation(_localDragOffset!);
705 706 707
    _startedOnSelectedSegment = index == highlightedIndex;
    pressedIndex = index;

708
    if (_startedOnSelectedSegment!) {
709 710 711 712 713 714
      _playThumbScaleAnimation(isExpanding: false);
    }
  }

  void _onUpdate(DragUpdateDetails details) {
    _localDragOffset = details.localPosition;
715
    final int? newIndex = indexFromLocation(_localDragOffset!);
716

717
    if (_startedOnSelectedSegment!) {
718 719 720 721 722 723 724 725
      highlightedIndex = newIndex;
      pressedIndex = newIndex;
    } else {
      pressedIndex = _hasDraggedTooFar(details) ? null : newIndex;
    }
  }

  void _onEnd(DragEndDetails details) {
726
    if (_startedOnSelectedSegment!) {
727 728 729 730 731 732 733 734 735 736 737 738 739 740
      _playThumbScaleAnimation(isExpanding: true);
      state.didChangeSelectedViaGesture();
    }

    if (pressedIndex != null) {
      highlightedIndex = pressedIndex;
      state.didChangeSelectedViaGesture();
    }
    pressedIndex = null;
    _localDragOffset = null;
    _startedOnSelectedSegment = null;
  }

  void _onCancel() {
741
    if (_startedOnSelectedSegment!) {
742 743 744 745 746 747 748 749
      _playThumbScaleAnimation(isExpanding: true);
    }

    _localDragOffset = null;
    pressedIndex = null;
    _startedOnSelectedSegment = null;
  }

750
  void _playThumbScaleAnimation({ required bool isExpanding }) {
751 752 753 754 755 756 757 758 759 760 761 762
    assert(isExpanding != null);
    _thumbScaleTween = Tween<double>(begin: currentThumbScale, end: isExpanding ? 1 : _kMinThumbScale);
    state.thumbScaleController.animateWith(_kThumbSpringAnimationSimulation);
  }

  bool _hasDraggedTooFar(DragUpdateDetails details) {
    final Offset offCenter = details.localPosition - Offset(size.width/2, size.height/2);
    return math.pow(math.max(0, offCenter.dx.abs() - size.width/2), 2) + math.pow(math.max(0, offCenter.dy.abs() - size.height/2), 2) > _kTouchYDistanceThreshold;
  }

  @override
  double computeMinIntrinsicWidth(double height) {
763
    RenderBox? child = firstChild;
764 765
    double maxMinChildWidth = 0;
    while (child != null) {
766
      final _SegmentedControlContainerBoxParentData childParentData =
767
        child.parentData! as _SegmentedControlContainerBoxParentData;
768 769 770 771 772 773 774 775 776
      final double childWidth = child.getMinIntrinsicWidth(height);
      maxMinChildWidth = math.max(maxMinChildWidth, childWidth);
      child = childParentData.nextSibling;
    }
    return (maxMinChildWidth + 2 * _kSegmentMinPadding) * childCount + totalSeparatorWidth;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
777
    RenderBox? child = firstChild;
778 779
    double maxMaxChildWidth = 0;
    while (child != null) {
780
      final _SegmentedControlContainerBoxParentData childParentData =
781
        child.parentData! as _SegmentedControlContainerBoxParentData;
782 783 784 785 786 787 788 789 790
      final double childWidth = child.getMaxIntrinsicWidth(height);
      maxMaxChildWidth = math.max(maxMaxChildWidth, childWidth);
      child = childParentData.nextSibling;
    }
    return (maxMaxChildWidth + 2 * _kSegmentMinPadding) * childCount + totalSeparatorWidth;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
791
    RenderBox? child = firstChild;
792 793
    double maxMinChildHeight = 0;
    while (child != null) {
794
      final _SegmentedControlContainerBoxParentData childParentData =
795
        child.parentData! as _SegmentedControlContainerBoxParentData;
796 797 798 799 800 801 802 803 804
      final double childHeight = child.getMinIntrinsicHeight(width);
      maxMinChildHeight = math.max(maxMinChildHeight, childHeight);
      child = childParentData.nextSibling;
    }
    return maxMinChildHeight;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
805
    RenderBox? child = firstChild;
806 807
    double maxMaxChildHeight = 0;
    while (child != null) {
808
      final _SegmentedControlContainerBoxParentData childParentData =
809
        child.parentData! as _SegmentedControlContainerBoxParentData;
810 811 812 813 814 815 816 817
      final double childHeight = child.getMaxIntrinsicHeight(width);
      maxMaxChildHeight = math.max(maxMaxChildHeight, childHeight);
      child = childParentData.nextSibling;
    }
    return maxMaxChildHeight;
  }

  @override
818
  double? computeDistanceToActualBaseline(TextBaseline baseline) {
819 820 821 822 823 824 825 826 827 828 829 830
    return defaultComputeDistanceToHighestActualBaseline(baseline);
  }

  @override
  void setupParentData(RenderBox child) {
    if (child.parentData is! _SegmentedControlContainerBoxParentData) {
      child.parentData = _SegmentedControlContainerBoxParentData();
    }
  }

  @override
  void performLayout() {
831
    final BoxConstraints constraints = this.constraints;
832 833 834
    double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount;
    double maxHeight = _kMinSegmentedControlHeight;

835
    for (final RenderBox child in getChildrenAsList()) {
836 837 838 839 840 841 842 843
      childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding);
    }

    childWidth = math.min(
      childWidth,
      (constraints.maxWidth - totalSeparatorWidth) / childCount,
    );

844
    RenderBox? child = firstChild;
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    while (child != null) {
      final double boxHeight = child.getMaxIntrinsicHeight(childWidth);
      maxHeight = math.max(maxHeight, boxHeight);
      child = childAfter(child);
    }

    constraints.constrainHeight(maxHeight);

    final BoxConstraints childConstraints = BoxConstraints.tightFor(
      width: childWidth,
      height: maxHeight,
    );

    // Layout children.
    child = firstChild;
    while (child != null) {
      child.layout(childConstraints, parentUsesSize: true);
      child = childAfter(child);
    }

    double start = 0;
    child = firstChild;

    while (child != null) {
869
      final _SegmentedControlContainerBoxParentData childParentData =
870
        child.parentData! as _SegmentedControlContainerBoxParentData;
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
      final Offset childOffset = Offset(start, 0);
      childParentData.offset = childOffset;
      start += child.size.width + _kSeparatorWidth + _kSeparatorInset.horizontal;
      child = childAfter(child);
    }

    size = constraints.constrain(Size(childWidth * childCount + totalSeparatorWidth, maxHeight));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final List<RenderBox> children = getChildrenAsList();

    // Paint thumb if highlightedIndex is not null.
    if (highlightedIndex != null) {
      if (_childAnimations == null) {
        _childAnimations = <RenderBox, _ChildAnimationManifest> { };
        for (int i = 0; i < childCount - 1; i += 1) {
          // The separator associated with the last child will not be painted (unless
          // a new trailing segment is added), and its opacity will always be 1.
891
          final bool shouldFadeOut = i == highlightedIndex || i == highlightedIndex! - 1;
892
          final RenderBox child = children[i];
893
          _childAnimations![child] = _ChildAnimationManifest(separatorOpacity: shouldFadeOut ? 0 : 1);
894 895 896
        }
      }

897
      final RenderBox selectedChild = children[highlightedIndex!];
898

899
      final _SegmentedControlContainerBoxParentData childParentData =
900
        selectedChild.parentData! as _SegmentedControlContainerBoxParentData;
901 902 903 904 905 906 907 908 909 910
      final Rect unscaledThumbTargetRect = _kThumbInsets.inflateRect(childParentData.offset & selectedChild.size);

      // Update related Tweens before animation update phase.
      if (_needsThumbAnimationUpdate) {
        // Needs to ensure _currentThumbRect is valid.
        _currentThumbTween = RectTween(begin: currentThumbRect ?? unscaledThumbTargetRect, end: unscaledThumbTargetRect);

        for (int i = 0; i < childCount - 1; i += 1) {
          // The separator associated with the last child will not be painted (unless
          // a new segment is appended to the child list), and its opacity will always be 1.
911
          final bool shouldFadeOut = i == highlightedIndex || i == highlightedIndex! - 1;
912
          final RenderBox child = children[i];
913
          final _ChildAnimationManifest manifest = _childAnimations![child]!;
914 915 916 917 918 919 920 921
          assert(manifest != null);
          manifest.separatorTween = Tween<double>(
            begin: manifest.separatorOpacity,
            end: shouldFadeOut ? 0 : 1,
          );
        }

        _needsThumbAnimationUpdate = false;
922 923
      } else if (_currentThumbTween != null && unscaledThumbTargetRect != _currentThumbTween!.begin) {
        _currentThumbTween = RectTween(begin: _currentThumbTween!.begin, end: unscaledThumbTargetRect);
924 925 926 927 928 929 930 931 932 933 934 935
      }

      for (int index = 0; index < childCount - 1; index += 1) {
        _paintSeparator(context, offset, children[index]);
      }

      currentThumbRect = _currentThumbTween?.evaluate(state.thumbController)
                        ?? unscaledThumbTargetRect;

      currentThumbScale = _thumbScaleTween.evaluate(state.thumbScaleController);

      final Rect thumbRect = Rect.fromCenter(
936 937 938
        center: currentThumbRect!.center,
        width: currentThumbRect!.width * currentThumbScale,
        height: currentThumbRect!.height * currentThumbScale,
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
      );

      _paintThumb(context, offset, thumbRect);
    } else {
      // Reset all animations when there's no thumb.
      currentThumbRect = null;
      _childAnimations = null;

      for (int index = 0; index < childCount - 1; index += 1) {
        _paintSeparator(context, offset, children[index]);
      }
    }

    for (int index = 0; index < children.length; index++) {
      _paintChild(context, offset, children[index], index);
    }
  }

  // Paint the separator to the right of the given child.
  void _paintSeparator(PaintingContext context, Offset offset, RenderBox child) {
    assert(child != null);
960
    final _SegmentedControlContainerBoxParentData childParentData =
961
      child.parentData! as _SegmentedControlContainerBoxParentData;
962 963 964

    final Paint paint = Paint();

965 966
    final _ChildAnimationManifest? manifest = _childAnimations == null ? null : _childAnimations![child];
    final double opacity = manifest?.separatorTween.evaluate(state.separatorOpacityController) ?? 1;
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    manifest?.separatorOpacity = opacity;
    paint.color = _kSeparatorColor.withOpacity(_kSeparatorColor.opacity * opacity);

    final Rect childRect = (childParentData.offset + offset) & child.size;
    final Rect separatorRect = _kSeparatorInset.deflateRect(
      childRect.topRight & Size(_kSeparatorInset.horizontal + _kSeparatorWidth, child.size.height),
    );

    context.canvas.drawRRect(
      RRect.fromRectAndRadius(separatorRect, _kSeparatorRadius),
      paint,
    );
  }

  void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) {
    assert(child != null);
983
    final _SegmentedControlContainerBoxParentData childParentData =
984
      child.parentData! as _SegmentedControlContainerBoxParentData;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    context.paintChild(child, childParentData.offset + offset);
  }

  void _paintThumb(PaintingContext context, Offset offset, Rect thumbRect) {
    // Colors extracted from https://developer.apple.com/design/resources/.
    const List<BoxShadow> thumbShadow = <BoxShadow> [
      BoxShadow(
        color: Color(0x1F000000),
        offset: Offset(0, 3),
        blurRadius: 8,
      ),
      BoxShadow(
        color: Color(0x0A000000),
        offset: Offset(0, 3),
        blurRadius: 1,
      ),
    ];

    final RRect thumbRRect = RRect.fromRectAndRadius(thumbRect.shift(offset), _kThumbRadius);

1005
    for (final BoxShadow shadow in thumbShadow) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
      context.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint());
    }

    context.canvas.drawRRect(
      thumbRRect.inflate(0.5),
      Paint()..color = const Color(0x0A000000),
    );

    context.canvas.drawRRect(
      thumbRRect,
1016
      Paint()..color = thumbColor!,
1017 1018 1019 1020
    );
  }

  @override
1021
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
1022
    assert(position != null);
1023
    RenderBox? child = lastChild;
1024
    while (child != null) {
1025
      final _SegmentedControlContainerBoxParentData childParentData =
1026
        child.parentData! as _SegmentedControlContainerBoxParentData;
1027
      if ((childParentData.offset & child.size).contains(position)) {
1028 1029 1030 1031 1032
        return result.addWithPaintOffset(
          offset: childParentData.offset,
          position: position,
          hitTest: (BoxHitTestResult result, Offset localOffset) {
            assert(localOffset == position - childParentData.offset);
1033
            return child!.hitTest(result, position: localOffset);
1034 1035 1036 1037 1038 1039 1040 1041
          },
        );
      }
      child = childParentData.previousSibling;
    }
    return false;
  }
}