action_sheet.dart 45.4 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
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:ui' show ImageFilter;

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

import 'colors.dart';
12
import 'interface_level.dart';
13
import 'scrollbar.dart';
14
import 'theme.dart';
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

const TextStyle _kActionSheetActionStyle = TextStyle(
  fontFamily: '.SF UI Text',
  inherit: false,
  fontSize: 20.0,
  fontWeight: FontWeight.w400,
  textBaseline: TextBaseline.alphabetic,
);

const TextStyle _kActionSheetContentStyle = TextStyle(
  fontFamily: '.SF UI Text',
  inherit: false,
  fontSize: 13.0,
  fontWeight: FontWeight.w400,
  color: _kContentTextColor,
  textBaseline: TextBaseline.alphabetic,
);

// Translucent, very light gray that is painted on top of the blurred backdrop
// as the action sheet's background color.
35 36 37 38 39 40 41
// TODO(LongCatIsLooong): https://github.com/flutter/flutter/issues/39272. Use
// System Materials once we have them.
// Extracted from https://developer.apple.com/design/resources/.
const Color _kBackgroundColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xC7F9F9F9),
  darkColor: Color(0xC7252525),
);
42 43 44

// Translucent, light gray that is painted on top of the blurred backdrop as
// the background color of a pressed button.
45 46 47 48 49 50 51 52 53 54 55 56 57 58
// Eye-balled from iOS 13 beta simulator.
const Color _kPressedColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xFFE1E1E1),
  darkColor: Color(0xFF2E2E2E),
);

const Color _kCancelPressedColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xFFECECEC),
  darkColor: Color(0xFF49494B),
);

// The gray color used for text that appears in the title area.
// Extracted from https://developer.apple.com/design/resources/.
const Color _kContentTextColor = Color(0xFF8F8F8F);
59 60 61 62

// Translucent gray that is painted on top of the blurred backdrop in the gap
// areas between the content section and actions section, as well as between
// buttons.
63 64
// Eye-balled from iOS 13 beta simulator.
const Color _kButtonDividerColor = _kContentTextColor;
65 66 67 68 69 70 71 72 73 74 75 76 77

const double _kBlurAmount = 20.0;
const double _kEdgeHorizontalPadding = 8.0;
const double _kCancelButtonPadding = 8.0;
const double _kEdgeVerticalPadding = 10.0;
const double _kContentHorizontalPadding = 40.0;
const double _kContentVerticalPadding = 14.0;
const double _kButtonHeight = 56.0;
const double _kCornerRadius = 14.0;
const double _kDividerThickness = 1.0;

/// An iOS-style action sheet.
///
78 79
/// {@youtube 560 315 https://www.youtube.com/watch?v=U-ao8p4A82k}
///
80 81 82 83 84 85 86 87 88 89
/// An action sheet is a specific style of alert that presents the user
/// with a set of two or more choices related to the current context.
/// An action sheet can have a title, an additional message, and a list
/// of actions. The title is displayed above the message and the actions
/// are displayed below this content.
///
/// This action sheet styles its title and message to match standard iOS action
/// sheet title and message text style.
///
/// To display action buttons that look like standard iOS action sheet buttons,
90 91
/// provide [CupertinoActionSheetAction]s for the [actions] given to this action
/// sheet.
92 93 94 95 96 97 98 99 100
///
/// To include a iOS-style cancel button separate from the other buttons,
/// provide an [CupertinoActionSheetAction] for the [cancelButton] given to this
/// action sheet.
///
/// An action sheet is typically passed as the child widget to
/// [showCupertinoModalPopup], which displays the action sheet by sliding it up
/// from the bottom of the screen.
///
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
/// {@tool snippet}
/// This sample shows how to use a [CupertinoActionSheet].
///	The [CupertinoActionSheet] shows an alert with a set of two choices
/// when [CupertinoButton] is pressed.
///
/// ```dart
/// class MyStatefulWidget extends StatefulWidget {
///   @override
///   _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
/// }
///
/// class _MyStatefulWidgetState extends State<MyStatefulWidget> {
///   @override
///   Widget build(BuildContext context) {
///     return CupertinoPageScaffold(
///       child: Center(
///         child: CupertinoButton(
///           onPressed: () {
///             showCupertinoModalPopup(
///               context: context,
///               builder: (BuildContext context) => CupertinoActionSheet(
///                 title: const Text('Title'),
///                 message: const Text('Message'),
///                 actions: [
///                   CupertinoActionSheetAction(
///                     child: const Text('Action One'),
///                     onPressed: () {
///                       Navigator.pop(context);
///                     },
///                   ),
///                   CupertinoActionSheetAction(
///                     child: const Text('Action Two'),
///                     onPressed: () {
///                       Navigator.pop(context);
///                     },
///                   )
///                 ],
///               ),
///             );
///           },
///           child: Text('CupertinoActionSheet'),
///         ),
///       ),
///     );
///   }
/// }
/// ```
/// {@end-tool}
///
150 151 152 153 154 155 156 157 158 159 160 161 162
/// See also:
///
///  * [CupertinoActionSheetAction], which is an iOS-style action sheet button.
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/views/action-sheets/>
class CupertinoActionSheet extends StatelessWidget {
  /// Creates an iOS-style action sheet.
  ///
  /// An action sheet must have a non-null value for at least one of the
  /// following arguments: [actions], [title], [message], or [cancelButton].
  ///
  /// Generally, action sheets are used to give the user a choice between
  /// two or more choices for the current context.
  const CupertinoActionSheet({
163
    Key? key,
164 165 166 167 168 169
    this.title,
    this.message,
    this.actions,
    this.messageScrollController,
    this.actionScrollController,
    this.cancelButton,
170
  }) : assert(actions != null || title != null || message != null || cancelButton != null,
171 172
          'An action sheet must have a non-null value for at least one of the following arguments: '
          'actions, title, message, or cancelButton'),
173
       super(key: key);
174 175 176 177 178

  /// An optional title of the action sheet. When the [message] is non-null,
  /// the font of the [title] is bold.
  ///
  /// Typically a [Text] widget.
179
  final Widget? title;
180 181 182 183 184

  /// An optional descriptive message that provides more details about the
  /// reason for the alert.
  ///
  /// Typically a [Text] widget.
185
  final Widget? message;
186 187 188 189

  /// The set of actions that are displayed for the user to select.
  ///
  /// Typically this is a list of [CupertinoActionSheetAction] widgets.
190
  final List<Widget>? actions;
191 192 193 194 195 196

  /// A scroll controller that can be used to control the scrolling of the
  /// [message] in the action sheet.
  ///
  /// This attribute is typically not needed, as alert messages should be
  /// short.
197
  final ScrollController? messageScrollController;
198 199 200 201 202

  /// A scroll controller that can be used to control the scrolling of the
  /// [actions] in the action sheet.
  ///
  /// This attribute is typically not needed.
203
  final ScrollController? actionScrollController;
204 205 206 207 208

  /// The optional cancel button that is grouped separately from the other
  /// actions.
  ///
  /// Typically this is an [CupertinoActionSheetAction] widget.
209
  final Widget? cancelButton;
210

211
  Widget _buildContent(BuildContext context) {
212 213
    final List<Widget> content = <Widget>[];
    if (title != null || message != null) {
214
      final Widget titleSection = _CupertinoAlertContentSection(
215 216 217 218
        title: title,
        message: message,
        scrollController: messageScrollController,
      );
219
      content.add(Flexible(child: titleSection));
220 221
    }

222
    return Container(
223
      color: CupertinoDynamicColor.resolve(_kBackgroundColor, context),
224
      child: Column(
225 226 227 228 229 230 231 232
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: content,
      ),
    );
  }

  Widget _buildActions() {
233
    if (actions == null || actions!.isEmpty) {
234
      return Container(
235 236 237
        height: 0.0,
      );
    }
238 239 240 241
    return _CupertinoAlertActionSection(
      children: actions!,
      scrollController: actionScrollController,
      hasCancelButton: cancelButton != null,
242 243 244 245 246 247 248
    );
  }

  Widget _buildCancelButton() {
    final double cancelPadding = (actions != null || message != null || title != null)
        ? _kCancelButtonPadding : 0.0;
    return Padding(
249 250
      padding: EdgeInsets.only(top: cancelPadding),
      child: _CupertinoActionSheetCancelButton(
251 252 253 254 255 256 257
        child: cancelButton,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
258 259
    assert(debugCheckHasMediaQuery(context));

260
    final List<Widget> children = <Widget>[
261
      Flexible(child: ClipRRect(
262 263 264
          borderRadius: BorderRadius.circular(12.0),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount),
265
            child: _CupertinoAlertRenderWidget(
266
              contentSection: Builder(builder: _buildContent),
267 268 269 270 271
              actionsSection: _buildActions(),
            ),
          ),
        ),
      ),
272
      if (cancelButton != null) _buildCancelButton(),
273 274
    ];

275
    final Orientation orientation = MediaQuery.of(context).orientation;
276
    final double actionSheetWidth;
277
    if (orientation == Orientation.portrait) {
278
      actionSheetWidth = MediaQuery.of(context).size.width - (_kEdgeHorizontalPadding * 2);
279
    } else {
280
      actionSheetWidth = MediaQuery.of(context).size.height - (_kEdgeHorizontalPadding * 2);
281 282
    }

283 284
    return SafeArea(
      child: Semantics(
285 286 287 288
        namesRoute: true,
        scopesRoute: true,
        explicitChildNodes: true,
        label: 'Alert',
289 290 291 292 293 294 295 296 297 298 299 300 301
        child: CupertinoUserInterfaceLevel(
          data: CupertinoUserInterfaceLevelData.elevated,
          child: Container(
            width: actionSheetWidth,
            margin: const EdgeInsets.symmetric(
              horizontal: _kEdgeHorizontalPadding,
              vertical: _kEdgeVerticalPadding,
            ),
            child: Column(
              children: children,
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
            ),
302 303 304 305 306 307 308 309 310 311 312 313 314 315
          ),
        ),
      ),
    );
  }
}

/// A button typically used in a [CupertinoActionSheet].
///
/// See also:
///
///  * [CupertinoActionSheet], an alert that presents the user with a set of two or
///    more choices related to the current context.
class CupertinoActionSheetAction extends StatelessWidget {
316
  /// Creates an action for an iOS-style action sheet.
317 318 319
  ///
  /// The [child] and [onPressed] arguments must not be null.
  const CupertinoActionSheetAction({
320 321
    Key? key,
    required this.onPressed,
322 323
    this.isDefaultAction = false,
    this.isDestructiveAction = false,
324
    required this.child,
325
  }) : assert(child != null),
326 327
       assert(onPressed != null),
       super(key: key);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

  /// The callback that is called when the button is tapped.
  ///
  /// This attribute must not be null.
  final VoidCallback onPressed;

  /// Whether this action is the default choice in the action sheet.
  ///
  /// Default buttons have bold text.
  final bool isDefaultAction;

  /// Whether this action might change or delete data.
  ///
  /// Destructive buttons have red text.
  final bool isDestructiveAction;

  /// The widget below this widget in the tree.
  ///
  /// Typically a [Text] widget.
  final Widget child;

  @override
  Widget build(BuildContext context) {
351 352
    TextStyle style = _kActionSheetActionStyle.copyWith(
      color: isDestructiveAction
353
        ? CupertinoDynamicColor.resolve(CupertinoColors.systemRed, context)
354 355
        : CupertinoTheme.of(context).primaryColor,
    );
356 357 358 359 360

    if (isDefaultAction) {
      style = style.copyWith(fontWeight: FontWeight.w600);
    }

361
    return GestureDetector(
362 363
      onTap: onPressed,
      behavior: HitTestBehavior.opaque,
364
      child: ConstrainedBox(
365 366 367
        constraints: const BoxConstraints(
          minHeight: _kButtonHeight,
        ),
368
        child: Semantics(
369
          button: true,
370
          child: Container(
371 372 373 374 375
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(
              vertical: 16.0,
              horizontal: 10.0,
            ),
376
            child: DefaultTextStyle(
377 378 379 380 381 382 383 384 385 386 387 388 389
              style: style,
              child: child,
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }
}

class _CupertinoActionSheetCancelButton extends StatefulWidget {
  const _CupertinoActionSheetCancelButton({
390
    Key? key,
391 392 393
    this.child,
  }) : super(key: key);

394
  final Widget? child;
395 396 397 398 399 400

  @override
  _CupertinoActionSheetCancelButtonState createState() => _CupertinoActionSheetCancelButtonState();
}

class _CupertinoActionSheetCancelButtonState extends State<_CupertinoActionSheetCancelButton> {
401
  bool isBeingPressed = false;
402 403

  void _onTapDown(TapDownDetails event) {
404
    setState(() { isBeingPressed = true; });
405 406 407
  }

  void _onTapUp(TapUpDetails event) {
408
    setState(() { isBeingPressed = false; });
409 410 411
  }

  void _onTapCancel() {
412
    setState(() { isBeingPressed = false; });
413 414 415 416
  }

  @override
  Widget build(BuildContext context) {
417 418
    final Color backgroundColor = isBeingPressed
      ? _kCancelPressedColor
419
      : CupertinoColors.secondarySystemGroupedBackground;
420
    return GestureDetector(
421 422 423 424
      excludeFromSemantics: true,
      onTapDown: _onTapDown,
      onTapUp: _onTapUp,
      onTapCancel: _onTapCancel,
425 426
      child: Container(
        decoration: BoxDecoration(
427
          color: CupertinoDynamicColor.resolve(backgroundColor, context),
428
          borderRadius: BorderRadius.circular(_kCornerRadius),
429 430 431 432 433 434 435 436 437
        ),
        child: widget.child,
      ),
    );
  }
}

class _CupertinoAlertRenderWidget extends RenderObjectWidget {
  const _CupertinoAlertRenderWidget({
438 439 440
    Key? key,
    required this.contentSection,
    required this.actionsSection,
441 442 443 444 445 446 447
  }) : super(key: key);

  final Widget contentSection;
  final Widget actionsSection;

  @override
  RenderObject createRenderObject(BuildContext context) {
448
    assert(debugCheckHasMediaQuery(context));
449
    return _RenderCupertinoAlert(
450
      dividerThickness: _kDividerThickness / MediaQuery.of(context).devicePixelRatio,
451
      dividerColor: CupertinoDynamicColor.resolve(_kButtonDividerColor, context),
452 453 454
    );
  }

455 456 457
  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoAlert renderObject) {
    super.updateRenderObject(context, renderObject);
458
    renderObject.dividerColor = CupertinoDynamicColor.resolve(_kButtonDividerColor, context);
459 460
  }

461 462 463 464 465 466 467 468 469
  @override
  RenderObjectElement createElement() {
    return _CupertinoAlertRenderElement(this);
  }
}

class _CupertinoAlertRenderElement extends RenderObjectElement {
  _CupertinoAlertRenderElement(_CupertinoAlertRenderWidget widget) : super(widget);

470 471
  Element? _contentElement;
  Element? _actionsElement;
472 473

  @override
474
  _CupertinoAlertRenderWidget get widget => super.widget as _CupertinoAlertRenderWidget;
475 476

  @override
477
  _RenderCupertinoAlert get renderObject => super.renderObject as _RenderCupertinoAlert;
478 479 480 481

  @override
  void visitChildren(ElementVisitor visitor) {
    if (_contentElement != null) {
482
      visitor(_contentElement!);
483 484
    }
    if (_actionsElement != null) {
485
      visitor(_actionsElement!);
486 487 488 489
    }
  }

  @override
490
  void mount(Element? parent, dynamic newSlot) {
491 492 493 494 495 496 497 498
    super.mount(parent, newSlot);
    _contentElement = updateChild(_contentElement,
        widget.contentSection, _AlertSections.contentSection);
    _actionsElement = updateChild(_actionsElement,
        widget.actionsSection, _AlertSections.actionsSection);
  }

  @override
499
  void insertRenderObjectChild(RenderObject child, _AlertSections slot) {
500 501 502 503
    _placeChildInSlot(child, slot);
  }

  @override
504 505
  void moveRenderObjectChild(RenderObject child, _AlertSections oldSlot, _AlertSections newSlot) {
    _placeChildInSlot(child, newSlot);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  }

  @override
  void update(RenderObjectWidget newWidget) {
    super.update(newWidget);
    _contentElement = updateChild(_contentElement,
        widget.contentSection, _AlertSections.contentSection);
    _actionsElement = updateChild(_actionsElement,
        widget.actionsSection, _AlertSections.actionsSection);
  }

  @override
  void forgetChild(Element child) {
    assert(child == _contentElement || child == _actionsElement);
    if (_contentElement == child) {
      _contentElement = null;
    } else if (_actionsElement == child) {
      _actionsElement = null;
    }
525
    super.forgetChild(child);
526 527 528
  }

  @override
529
  void removeRenderObjectChild(RenderObject child, _AlertSections slot) {
530 531 532 533 534
    assert(child == renderObject.contentSection || child == renderObject.actionsSection);
    if (renderObject.contentSection == child) {
      renderObject.contentSection = null;
    } else if (renderObject.actionsSection == child) {
      renderObject.actionsSection = null;
535 536 537 538 539 540 541
    }
  }

  void _placeChildInSlot(RenderObject child, _AlertSections slot) {
    assert(slot != null);
    switch (slot) {
      case _AlertSections.contentSection:
542
        renderObject.contentSection = child as RenderBox;
543 544
        break;
      case _AlertSections.actionsSection:
545
        renderObject.actionsSection = child as RenderBox;
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
        break;
    }
  }
}

// An iOS-style layout policy for sizing an alert's content section and action
// button section.
//
// The policy is as follows:
//
// If all content and buttons fit on the screen:
// The content section and action button section are sized intrinsically.
//
// If all content and buttons do not fit on the screen:
// A minimum height for the action button section is calculated. The action
// button section will not be rendered shorter than this minimum.  See
// _RenderCupertinoAlertActions for the minimum height calculation.
//
// With the minimum action button section calculated, the content section can
// take up as much of the remaining space as it needs.
//
// After the content section is laid out, the action button section is allowed
// to take up any remaining space that was not consumed by the content section.
class _RenderCupertinoAlert extends RenderBox {
  _RenderCupertinoAlert({
571 572
    RenderBox? contentSection,
    RenderBox? actionsSection,
573
    double dividerThickness = 0.0,
574
    required Color dividerColor,
575 576
  }) : assert(dividerColor != null),
       _contentSection = contentSection,
577
       _actionsSection = actionsSection,
578 579 580 581
       _dividerThickness = dividerThickness,
       _dividerPaint = Paint()
        ..color = dividerColor
        ..style = PaintingStyle.fill;
582

583 584 585
  RenderBox? get contentSection => _contentSection;
  RenderBox? _contentSection;
  set contentSection(RenderBox? newContentSection) {
586 587
    if (newContentSection != _contentSection) {
      if (null != _contentSection) {
588
        dropChild(_contentSection!);
589 590 591
      }
      _contentSection = newContentSection;
      if (null != _contentSection) {
592
        adoptChild(_contentSection!);
593 594 595 596
      }
    }
  }

597 598 599
  RenderBox? get actionsSection => _actionsSection;
  RenderBox? _actionsSection;
  set actionsSection(RenderBox? newActionsSection) {
600 601
    if (newActionsSection != _actionsSection) {
      if (null != _actionsSection) {
602
        dropChild(_actionsSection!);
603 604 605
      }
      _actionsSection = newActionsSection;
      if (null != _actionsSection) {
606
        adoptChild(_actionsSection!);
607 608 609 610
      }
    }
  }

611 612 613 614 615 616 617 618
  Color get dividerColor => _dividerPaint.color;
  set dividerColor(Color value) {
    if (value == _dividerPaint.color)
      return;
    _dividerPaint.color = value;
    markNeedsPaint();
  }

619 620
  final double _dividerThickness;

621
  final Paint _dividerPaint;
622 623 624 625 626

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    if (null != contentSection) {
627
      contentSection!.attach(owner);
628 629
    }
    if (null != actionsSection) {
630
      actionsSection!.attach(owner);
631 632 633 634 635 636 637
    }
  }

  @override
  void detach() {
    super.detach();
    if (null != contentSection) {
638
      contentSection!.detach();
639 640
    }
    if (null != actionsSection) {
641
      actionsSection!.detach();
642 643 644 645 646 647
    }
  }

  @override
  void redepthChildren() {
    if (null != contentSection) {
648
      redepthChild(contentSection!);
649 650
    }
    if (null != actionsSection) {
651
      redepthChild(actionsSection!);
652 653 654 655 656 657
    }
  }

  @override
  void setupParentData(RenderBox child) {
    if (child.parentData is! MultiChildLayoutParentData) {
658
      child.parentData = MultiChildLayoutParentData();
659 660 661 662 663 664
    }
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    if (contentSection != null) {
665
      visitor(contentSection!);
666 667
    }
    if (actionsSection != null) {
668
      visitor(actionsSection!);
669 670 671 672 673 674 675
    }
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> value = <DiagnosticsNode>[];
    if (contentSection != null) {
676
      value.add(contentSection!.toDiagnosticsNode(name: 'content'));
677 678
    }
    if (actionsSection != null) {
679
      value.add(actionsSection!.toDiagnosticsNode(name: 'actions'));
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    }
    return value;
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    return constraints.minWidth;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    return constraints.maxWidth;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
696 697
    final double contentHeight = contentSection!.getMinIntrinsicHeight(width);
    final double actionsHeight = actionsSection!.getMinIntrinsicHeight(width);
698 699 700 701 702 703 704 705 706 707 708 709
    final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0;
    double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight;

    if (actionsHeight > 0 || contentHeight > 0)
      height -= 2 * _kEdgeVerticalPadding;
    if (height.isFinite)
      return height;
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
710 711
    final double contentHeight = contentSection!.getMaxIntrinsicHeight(width);
    final double actionsHeight = actionsSection!.getMaxIntrinsicHeight(width);
712 713 714 715 716 717 718 719 720 721
    final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0;
    double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight;

    if (actionsHeight > 0 || contentHeight > 0)
      height -= 2 * _kEdgeVerticalPadding;
    if (height.isFinite)
      return height;
    return 0.0;
  }

722
  double _computeDividerThickness(BoxConstraints constraints) {
723 724
    final bool hasDivider = contentSection!.getMaxIntrinsicHeight(constraints.maxWidth) > 0.0
        && actionsSection!.getMaxIntrinsicHeight(constraints.maxWidth) > 0.0;
725 726
    return hasDivider ? _dividerThickness : 0.0;
  }
727

728
  _AlertSizes _computeSizes({required BoxConstraints constraints, required ChildLayouter layoutChild, required double dividerThickness}) {
729
    final double minActionsHeight = actionsSection!.getMinIntrinsicHeight(constraints.maxWidth);
730

731 732
    final Size contentSize = layoutChild(
      contentSection!,
733
      constraints.deflate(EdgeInsets.only(bottom: minActionsHeight + dividerThickness)),
734 735
    );

736 737
    final Size actionsSize = layoutChild(
      actionsSection!,
738
      constraints.deflate(EdgeInsets.only(top: contentSize.height + dividerThickness)),
739 740 741
    );

    final double actionSheetHeight = contentSize.height + dividerThickness + actionsSize.height;
742 743 744 745 746
    return _AlertSizes(
      size: Size(constraints.maxWidth, actionSheetHeight),
      contentHeight: contentSize.height,
    );
  }
747

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return _computeSizes(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.dryLayoutChild,
      dividerThickness: _computeDividerThickness(constraints),
    ).size;
  }

  @override
  void performLayout() {
    final BoxConstraints constraints = this.constraints;
    final double dividerThickness = _computeDividerThickness(constraints);
    final _AlertSizes alertSizes = _computeSizes(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.layoutChild,
      dividerThickness: dividerThickness,
    );

    size = alertSizes.size;
768 769 770

    // Set the position of the actions box to sit at the bottom of the alert.
    // The content box defaults to the top left, which is where we want it.
771
    assert(actionsSection!.parentData is MultiChildLayoutParentData);
772
    final MultiChildLayoutParentData actionParentData = actionsSection!.parentData! as MultiChildLayoutParentData;
773
    actionParentData.offset = Offset(0.0, alertSizes.contentHeight + dividerThickness);
774 775 776 777
  }

  @override
  void paint(PaintingContext context, Offset offset) {
778
    final MultiChildLayoutParentData contentParentData = contentSection!.parentData! as MultiChildLayoutParentData;
779
    contentSection!.paint(context, offset + contentParentData.offset);
780

781
    final bool hasDivider = contentSection!.size.height > 0.0 && actionsSection!.size.height > 0.0;
782 783 784 785
    if (hasDivider) {
      _paintDividerBetweenContentAndActions(context.canvas, offset);
    }

786
    final MultiChildLayoutParentData actionsParentData = actionsSection!.parentData! as MultiChildLayoutParentData;
787
    actionsSection!.paint(context, offset + actionsParentData.offset);
788 789 790 791 792 793
  }

  void _paintDividerBetweenContentAndActions(Canvas canvas, Offset offset) {
    canvas.drawRect(
      Rect.fromLTWH(
        offset.dx,
794
        offset.dy + contentSection!.size.height,
795 796 797 798 799 800 801 802
        size.width,
        _dividerThickness,
      ),
      _dividerPaint,
    );
  }

  @override
803
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
804 805
    final MultiChildLayoutParentData contentSectionParentData = contentSection!.parentData! as MultiChildLayoutParentData;
    final MultiChildLayoutParentData actionsSectionParentData = actionsSection!.parentData! as MultiChildLayoutParentData;
806 807 808 809 810
    return result.addWithPaintOffset(
             offset: contentSectionParentData.offset,
             position: position,
             hitTest: (BoxHitTestResult result, Offset transformed) {
               assert(transformed == position - contentSectionParentData.offset);
811
               return contentSection!.hitTest(result, position: transformed);
812 813 814 815 816 817 818
             },
           )
        || result.addWithPaintOffset(
             offset: actionsSectionParentData.offset,
             position: position,
             hitTest: (BoxHitTestResult result, Offset transformed) {
               assert(transformed == position - actionsSectionParentData.offset);
819
               return actionsSection!.hitTest(result, position: transformed);
820 821
             },
           );
822 823 824
  }
}

825 826 827 828 829 830 831
class _AlertSizes {
  const _AlertSizes({required this.size, required this.contentHeight});

  final Size size;
  final double contentHeight;
}

832 833 834 835 836 837 838 839 840 841 842 843 844 845
// Visual components of an alert that need to be explicitly sized and
// laid out at runtime.
enum _AlertSections {
  contentSection,
  actionsSection,
}

// The "content section" of a CupertinoActionSheet.
//
// If title is missing, then only content is added.  If content is
// missing, then only a title is added. If both are missing, then it returns
// a SingleChildScrollView with a zero-sized Container.
class _CupertinoAlertContentSection extends StatelessWidget {
  const _CupertinoAlertContentSection({
846
    Key? key,
847 848 849 850 851 852 853 854 855
    this.title,
    this.message,
    this.scrollController,
  }) : super(key: key);

  // An optional title of the action sheet. When the message is non-null,
  // the font of the title is bold.
  //
  // Typically a Text widget.
856
  final Widget? title;
857 858 859 860 861

  // An optional descriptive message that provides more details about the
  // reason for the alert.
  //
  // Typically a Text widget.
862
  final Widget? message;
863 864 865 866 867 868

  // A scroll controller that can be used to control the scrolling of the
  // content in the action sheet.
  //
  // Defaults to null, and is typically not needed, since most alert contents
  // are short.
869
  final ScrollController? scrollController;
870 871 872 873

  @override
  Widget build(BuildContext context) {
    final List<Widget> titleContentGroup = <Widget>[];
874

875
    if (title != null) {
876
      titleContentGroup.add(Padding(
877 878 879 880 881 882
        padding: const EdgeInsets.only(
          left: _kContentHorizontalPadding,
          right: _kContentHorizontalPadding,
          bottom: _kContentVerticalPadding,
          top: _kContentVerticalPadding,
        ),
883
        child: DefaultTextStyle(
884 885 886
          style: message == null ? _kActionSheetContentStyle
              : _kActionSheetContentStyle.copyWith(fontWeight: FontWeight.w600),
          textAlign: TextAlign.center,
887
          child: title!,
888 889 890 891 892 893
        ),
      ));
    }

    if (message != null) {
      titleContentGroup.add(
894 895
        Padding(
          padding: EdgeInsets.only(
896 897 898 899 900
            left: _kContentHorizontalPadding,
            right: _kContentHorizontalPadding,
            bottom: title == null ? _kContentVerticalPadding : 22.0,
            top: title == null ? _kContentVerticalPadding : 0.0,
          ),
901
          child: DefaultTextStyle(
902 903 904
            style: title == null ? _kActionSheetContentStyle.copyWith(fontWeight: FontWeight.w600)
                : _kActionSheetContentStyle,
            textAlign: TextAlign.center,
905
            child: message!,
906 907 908 909 910 911
          ),
        ),
      );
    }

    if (titleContentGroup.isEmpty) {
912
      return SingleChildScrollView(
913
        controller: scrollController,
914
        child: const SizedBox(
915 916 917 918 919 920 921 922 923 924 925
          width: 0.0,
          height: 0.0,
        ),
      );
    }

    // Add padding between the widgets if necessary.
    if (titleContentGroup.length > 1) {
      titleContentGroup.insert(1, const Padding(padding: EdgeInsets.only(top: 8.0)));
    }

926 927
    return CupertinoScrollbar(
      child: SingleChildScrollView(
928
        controller: scrollController,
929
        child: Column(
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: titleContentGroup,
        ),
      ),
    );
  }
}

// The "actions section" of a CupertinoActionSheet.
//
// See _RenderCupertinoAlertActions for details about action button sizing
// and layout.
class _CupertinoAlertActionSection extends StatefulWidget {
  const _CupertinoAlertActionSection({
945 946
    Key? key,
    required this.children,
947 948
    this.scrollController,
    this.hasCancelButton,
949 950
  }) : assert(children != null),
       super(key: key);
951 952 953 954 955 956 957 958

  final List<Widget> children;

  // A scroll controller that can be used to control the scrolling of the
  // actions in the action sheet.
  //
  // Defaults to null, and is typically not needed, since most alerts
  // don't have many actions.
959
  final ScrollController? scrollController;
960

961
  final bool? hasCancelButton;
962 963

  @override
964
  _CupertinoAlertActionSectionState createState() => _CupertinoAlertActionSectionState();
965 966 967 968 969
}

class _CupertinoAlertActionSectionState extends State<_CupertinoAlertActionSection> {
  @override
  Widget build(BuildContext context) {
970
    final double devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
971 972 973 974

    final List<Widget> interactiveButtons = <Widget>[];
    for (int i = 0; i < widget.children.length; i += 1) {
      interactiveButtons.add(
975
        _PressableActionButton(
976 977 978 979 980
          child: widget.children[i],
        ),
      );
    }

981 982
    return CupertinoScrollbar(
      child: SingleChildScrollView(
983
        controller: widget.scrollController,
984
        child: _CupertinoAlertActionsRenderWidget(
985 986
          actionButtons: interactiveButtons,
          dividerThickness: _kDividerThickness / devicePixelRatio,
987
          hasCancelButton: widget.hasCancelButton ?? false,
988 989 990 991 992 993 994 995 996 997 998 999 1000
        ),
      ),
    );
  }
}

// A button that updates its render state when pressed.
//
// The pressed state is forwarded to an _ActionButtonParentDataWidget. The
// corresponding _ActionButtonParentData is then interpreted and rendered
// appropriately by _RenderCupertinoAlertActions.
class _PressableActionButton extends StatefulWidget {
  const _PressableActionButton({
1001
    required this.child,
1002 1003 1004 1005 1006
  });

  final Widget child;

  @override
1007
  _PressableActionButtonState createState() => _PressableActionButtonState();
1008 1009 1010 1011 1012 1013 1014
}

class _PressableActionButtonState extends State<_PressableActionButton> {
  bool _isPressed = false;

  @override
  Widget build(BuildContext context) {
1015
    return _ActionButtonParentDataWidget(
1016
      isPressed: _isPressed,
1017 1018
      // TODO(mattcarroll): Button press dynamics need overhaul for iOS:
      //  https://github.com/flutter/flutter/issues/19786
1019
      child: GestureDetector(
1020 1021 1022 1023
        excludeFromSemantics: true,
        behavior: HitTestBehavior.opaque,
        onTapDown: (TapDownDetails details) => setState(() => _isPressed = true),
        onTapUp: (TapUpDetails details) => setState(() => _isPressed = false),
1024 1025
        // TODO(mattcarroll): Cancel is currently triggered when user moves past
        //  slop instead of off button: https://github.com/flutter/flutter/issues/19783
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        onTapCancel: () => setState(() => _isPressed = false),
        child: widget.child,
      ),
    );
  }
}

// ParentDataWidget that updates _ActionButtonParentData for an action button.
//
// Each action button requires knowledge of whether or not it is pressed so that
// the alert can correctly render the button. The pressed state is held within
// _ActionButtonParentData. _ActionButtonParentDataWidget is responsible for
// updating the pressed state of an _ActionButtonParentData based on the
// incoming isPressed property.
1040
class _ActionButtonParentDataWidget extends ParentDataWidget<_ActionButtonParentData> {
1041
  const _ActionButtonParentDataWidget({
1042 1043 1044
    Key? key,
    required this.isPressed,
    required Widget child,
1045 1046 1047 1048 1049 1050 1051
  }) : super(key: key, child: child);

  final bool isPressed;

  @override
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is _ActionButtonParentData);
1052
    final _ActionButtonParentData parentData = renderObject.parentData! as _ActionButtonParentData;
1053 1054 1055 1056
    if (parentData.isPressed != isPressed) {
      parentData.isPressed = isPressed;

      // Force a repaint.
1057
      final AbstractNode? targetParent = renderObject.parent;
1058 1059 1060 1061
      if (targetParent is RenderObject)
        targetParent.markNeedsPaint();
    }
  }
1062 1063 1064

  @override
  Type get debugTypicalAncestorWidgetClass => _CupertinoAlertActionsRenderWidget;
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
}

// ParentData applied to individual action buttons that report whether or not
// that button is currently pressed by the user.
class _ActionButtonParentData extends MultiChildLayoutParentData {
  _ActionButtonParentData({
    this.isPressed = false,
  });

  bool isPressed;
}

// An iOS-style alert action button layout.
//
// See _RenderCupertinoAlertActions for specific layout policy details.
class _CupertinoAlertActionsRenderWidget extends MultiChildRenderObjectWidget {
  _CupertinoAlertActionsRenderWidget({
1082 1083
    Key? key,
    required List<Widget> actionButtons,
1084 1085
    double dividerThickness = 0.0,
    bool hasCancelButton = false,
1086 1087 1088
  }) : _dividerThickness = dividerThickness,
       _hasCancelButton = hasCancelButton,
       super(key: key, children: actionButtons);
1089 1090 1091 1092 1093 1094

  final double _dividerThickness;
  final bool _hasCancelButton;

  @override
  RenderObject createRenderObject(BuildContext context) {
1095
    return _RenderCupertinoAlertActions(
1096
      dividerThickness: _dividerThickness,
1097
      dividerColor: CupertinoDynamicColor.resolve(_kButtonDividerColor, context),
1098
      hasCancelButton: _hasCancelButton,
1099 1100
      backgroundColor: CupertinoDynamicColor.resolve(_kBackgroundColor, context),
      pressedColor: CupertinoDynamicColor.resolve(_kPressedColor, context),
1101 1102 1103 1104 1105
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoAlertActions renderObject) {
1106 1107
    renderObject
      ..dividerThickness = _dividerThickness
1108
      ..dividerColor = CupertinoDynamicColor.resolve(_kButtonDividerColor, context)
1109
      ..hasCancelButton = _hasCancelButton
1110 1111
      ..backgroundColor = CupertinoDynamicColor.resolve(_kBackgroundColor, context)
      ..pressedColor = CupertinoDynamicColor.resolve(_kPressedColor, context);
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  }
}

// An iOS-style layout policy for sizing and positioning an action sheet's
// buttons.
//
// The policy is as follows:
//
// Action sheet buttons are always stacked vertically. In the case where the
// content section and the action section combined can not fit on the screen
// without scrolling, the height of the action section is determined as
// follows.
//
// If the user has included a separate cancel button, the height of the action
// section can be up to the height of 3 action buttons (i.e., the user can
// include 1, 2, or 3 action buttons and they will appear without needing to
// be scrolled). If 4+ action buttons are provided, the height of the action
// section shrinks to 1.5 buttons tall, and is scrollable.
//
// If the user has not included a separate cancel button, the height of the
// action section is at most 1.5 buttons tall.
class _RenderCupertinoAlertActions extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, MultiChildLayoutParentData>,
        RenderBoxContainerDefaultsMixin<RenderBox, MultiChildLayoutParentData> {
  _RenderCupertinoAlertActions({
1137
    List<RenderBox>? children,
1138
    double dividerThickness = 0.0,
1139
    required Color dividerColor,
1140
    bool hasCancelButton = false,
1141 1142
    required Color backgroundColor,
    required Color pressedColor,
1143
  }) : _dividerThickness = dividerThickness,
1144 1145 1146 1147 1148 1149 1150 1151 1152
       _hasCancelButton = hasCancelButton,
       _buttonBackgroundPaint = Paint()
          ..style = PaintingStyle.fill
          ..color = backgroundColor,
       _pressedButtonBackgroundPaint = Paint()
          ..style = PaintingStyle.fill
          ..color = pressedColor,
       _dividerPaint = Paint()
          ..color = dividerColor
1153 1154 1155
          ..style = PaintingStyle.fill {
    addAll(children);
  }
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

  // The thickness of the divider between buttons.
  double get dividerThickness => _dividerThickness;
  double _dividerThickness;
  set dividerThickness(double newValue) {
    if (newValue == _dividerThickness) {
      return;
    }

    _dividerThickness = newValue;
    markNeedsLayout();
  }

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
  Color get backgroundColor => _buttonBackgroundPaint.color;
  set backgroundColor(Color newValue) {
    if (newValue == _buttonBackgroundPaint.color) {
      return;
    }

    _buttonBackgroundPaint.color = newValue;
    markNeedsPaint();
  }

  Color get pressedColor => _pressedButtonBackgroundPaint.color;
  set pressedColor(Color newValue) {
    if (newValue == _pressedButtonBackgroundPaint.color) {
      return;
    }

    _pressedButtonBackgroundPaint.color = newValue;
    markNeedsPaint();
  }

  Color get dividerColor => _dividerPaint.color;
  set dividerColor(Color value) {
    if (value == _dividerPaint.color) {
      return;
    }
    _dividerPaint.color = value;
    markNeedsPaint();
  }

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
  bool _hasCancelButton;
  bool get hasCancelButton => _hasCancelButton;
  set hasCancelButton(bool newValue) {
    if (newValue == _hasCancelButton) {
      return;
    }

    _hasCancelButton = newValue;
    markNeedsLayout();
  }

1209 1210
  final Paint _buttonBackgroundPaint;
  final Paint _pressedButtonBackgroundPaint;
1211

1212
  final Paint _dividerPaint;
1213 1214 1215 1216

  @override
  void setupParentData(RenderBox child) {
    if (child.parentData is! _ActionButtonParentData)
1217
      child.parentData = _ActionButtonParentData();
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    return constraints.minWidth;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    return constraints.maxWidth;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    if (childCount == 0)
      return 0.0;
    if (childCount == 1)
1235
      return firstChild!.computeMaxIntrinsicHeight(width) + dividerThickness;
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    if (hasCancelButton && childCount < 4)
      return _computeMinIntrinsicHeightWithCancel(width);
    return _computeMinIntrinsicHeightWithoutCancel(width);
  }

  // The minimum height for more than 2-3 buttons when a cancel button is
  // included is the full height of button stack.
  double _computeMinIntrinsicHeightWithCancel(double width) {
    assert(childCount == 2 || childCount == 3);
    if (childCount == 2) {
1246 1247
      return firstChild!.getMinIntrinsicHeight(width)
        + childAfter(firstChild!)!.getMinIntrinsicHeight(width)
1248 1249
        + dividerThickness;
    }
1250 1251 1252
    return firstChild!.getMinIntrinsicHeight(width)
      + childAfter(firstChild!)!.getMinIntrinsicHeight(width)
      + childAfter(childAfter(firstChild!)!)!.getMinIntrinsicHeight(width)
1253 1254 1255 1256 1257 1258 1259 1260
      + (dividerThickness * 2);
  }

  // The minimum height for more than 2 buttons when no cancel button or 4+
  // buttons when a cancel button is included is the height of the 1st button
  // + 50% the height of the 2nd button + 2 dividers.
  double _computeMinIntrinsicHeightWithoutCancel(double width) {
    assert(childCount >= 2);
1261
    return firstChild!.getMinIntrinsicHeight(width)
1262
      + dividerThickness
1263
      + (0.5 * childAfter(firstChild!)!.getMinIntrinsicHeight(width));
1264 1265 1266 1267 1268 1269 1270
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    if (childCount == 0)
      return 0.0;
    if (childCount == 1)
1271
      return firstChild!.computeMaxIntrinsicHeight(width) + dividerThickness;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    return _computeMaxIntrinsicHeightStacked(width);
  }

  // Max height of a stack of buttons is the sum of all button heights + a
  // divider for each button.
  double _computeMaxIntrinsicHeightStacked(double width) {
    assert(childCount >= 2);

    final double allDividersHeight = (childCount - 1) * dividerThickness;
    double heightAccumulation = allDividersHeight;
1282
    RenderBox? button = firstChild;
1283 1284 1285 1286 1287 1288 1289
    while (button != null) {
      heightAccumulation += button.getMaxIntrinsicHeight(width);
      button = childAfter(button);
    }
    return heightAccumulation;
  }

1290 1291 1292 1293 1294
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return _performLayout(constraints, dry: true);
  }

1295 1296
  @override
  void performLayout() {
1297 1298 1299 1300
    size = _performLayout(constraints, dry: false);
  }

  Size _performLayout(BoxConstraints constraints, {bool dry = false}) {
1301 1302 1303 1304 1305
    final BoxConstraints perButtonConstraints = constraints.copyWith(
      minHeight: 0.0,
      maxHeight: double.infinity,
    );

1306
    RenderBox? child = firstChild;
1307 1308 1309
    int index = 0;
    double verticalOffset = 0.0;
    while (child != null) {
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
      final Size childSize;
      if (!dry) {
        child.layout(
          perButtonConstraints,
          parentUsesSize: true,
        );
        childSize = child.size;
        assert(child.parentData is MultiChildLayoutParentData);
        final MultiChildLayoutParentData parentData = child.parentData! as MultiChildLayoutParentData;
        parentData.offset = Offset(0.0, verticalOffset);
      } else {
        childSize = child.getDryLayout(constraints);
      }
1323

1324
      verticalOffset += childSize.height;
1325 1326 1327 1328 1329 1330 1331 1332 1333
      if (index < childCount - 1) {
        // Add a gap for the next divider.
        verticalOffset += dividerThickness;
      }

      index += 1;
      child = childAfter(child);
    }

1334
    return constraints.constrain(
1335
      Size(constraints.maxWidth, verticalOffset)
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    );
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;
    _drawButtonBackgroundsAndDividersStacked(canvas, offset);
    _drawButtons(context, offset);
  }

  void _drawButtonBackgroundsAndDividersStacked(Canvas canvas, Offset offset) {
1347
    final Offset dividerOffset = Offset(0.0, dividerThickness);
1348

1349
    final Path backgroundFillPath = Path()
1350
      ..fillType = PathFillType.evenOdd
1351
      ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height));
1352

1353
    final Path pressedBackgroundFillPath = Path();
1354

1355
    final Path dividersPath = Path();
1356 1357 1358

    Offset accumulatingOffset = offset;

1359 1360
    RenderBox? child = firstChild;
    RenderBox? prevChild;
1361 1362
    while (child != null) {
      assert(child.parentData is _ActionButtonParentData);
1363
      final _ActionButtonParentData currentButtonParentData = child.parentData! as _ActionButtonParentData;
1364 1365 1366 1367 1368
      final bool isButtonPressed = currentButtonParentData.isPressed;

      bool isPrevButtonPressed = false;
      if (prevChild != null) {
        assert(prevChild.parentData is _ActionButtonParentData);
1369
        final _ActionButtonParentData previousButtonParentData = prevChild.parentData! as _ActionButtonParentData;
1370 1371 1372 1373 1374
        isPrevButtonPressed = previousButtonParentData.isPressed;
      }

      final bool isDividerPresent = child != firstChild;
      final bool isDividerPainted = isDividerPresent && !(isButtonPressed || isPrevButtonPressed);
1375
      final Rect dividerRect = Rect.fromLTWH(
1376 1377 1378 1379 1380 1381
        accumulatingOffset.dx,
        accumulatingOffset.dy,
        size.width,
        _dividerThickness,
      );

1382
      final Rect buttonBackgroundRect = Rect.fromLTWH(
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
        accumulatingOffset.dx,
        accumulatingOffset.dy + (isDividerPresent ? dividerThickness : 0.0),
        size.width,
        child.size.height,
      );

      // If this button is pressed, then we don't want a white background to be
      // painted, so we erase this button from the background path.
      if (isButtonPressed) {
        backgroundFillPath.addRect(buttonBackgroundRect);
        pressedBackgroundFillPath.addRect(buttonBackgroundRect);
      }

      // If this divider is needed, then we erase the divider area from the
      // background path, and on top of that we paint a translucent gray to
      // darken the divider area.
      if (isDividerPainted) {
        backgroundFillPath.addRect(dividerRect);
        dividersPath.addRect(dividerRect);
      }

      accumulatingOffset += (isDividerPresent ? dividerOffset : Offset.zero)
1405
          + Offset(0.0, child.size.height);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

      prevChild = child;
      child = childAfter(child);
    }

    canvas.drawPath(backgroundFillPath, _buttonBackgroundPaint);
    canvas.drawPath(pressedBackgroundFillPath, _pressedButtonBackgroundPaint);
    canvas.drawPath(dividersPath, _dividerPaint);
  }

  void _drawButtons(PaintingContext context, Offset offset) {
1417
    RenderBox? child = firstChild;
1418
    while (child != null) {
1419
      final MultiChildLayoutParentData childParentData = child.parentData! as MultiChildLayoutParentData;
1420 1421 1422 1423 1424 1425
      context.paintChild(child, childParentData.offset + offset);
      child = childAfter(child);
    }
  }

  @override
1426
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
1427 1428 1429
    return defaultHitTestChildren(result, position: position);
  }
}