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

5
import 'dart:math' as math;
xster's avatar
xster committed
6
import 'dart:ui' show ImageFilter;
7 8 9

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

xster's avatar
xster committed
12
import 'colors.dart';
13
import 'interface_level.dart';
14
import 'localizations.dart';
15
import 'scrollbar.dart';
xster's avatar
xster committed
16

17 18
// TODO(abarth): These constants probably belong somewhere more general.

19 20 21 22 23
// Used XD to flutter plugin(https://github.com/AdobeXD/xd-to-flutter-plugin/)
// to derive values of TextStyle(height and letterSpacing) from
// Adobe XD template for iOS 13, which can be found in
// Apple Design Resources(https://developer.apple.com/design/resources/).
// However the values are not exactly the same as native, so eyeballing is needed.
24
const TextStyle _kCupertinoDialogTitleStyle = TextStyle(
25 26
  fontFamily: '.SF UI Display',
  inherit: false,
27
  fontSize: 17.0,
28
  fontWeight: FontWeight.w600,
29 30
  height: 1.3,
  letterSpacing: -0.5,
31 32 33
  textBaseline: TextBaseline.alphabetic,
);

34
const TextStyle _kCupertinoDialogContentStyle = TextStyle(
35 36
  fontFamily: '.SF UI Text',
  inherit: false,
37
  fontSize: 13.0,
38
  fontWeight: FontWeight.w400,
39 40
  height: 1.35,
  letterSpacing: -0.2,
41 42 43
  textBaseline: TextBaseline.alphabetic,
);

44
const TextStyle _kCupertinoDialogActionStyle = TextStyle(
45 46
  fontFamily: '.SF UI Text',
  inherit: false,
47
  fontSize: 16.8,
48 49 50 51
  fontWeight: FontWeight.w400,
  textBaseline: TextBaseline.alphabetic,
);

52 53 54
// iOS dialogs have a normal display width and another display width that is
// used when the device is in accessibility mode. Each of these widths are
// listed below.
55
const double _kCupertinoDialogWidth = 270.0;
56 57 58
const double _kAccessibilityCupertinoDialogWidth = 310.0;

const double _kBlurAmount = 20.0;
59
const double _kEdgePadding = 20.0;
60 61
const double _kMinButtonHeight = 45.0;
const double _kMinButtonFontSize = 10.0;
62
const double _kDialogCornerRadius = 14.0;
63
const double _kDividerThickness = 1.0;
64

65 66 67 68 69 70 71
// A translucent color that is painted on top of the blurred backdrop as the
// dialog's background color
// Extracted from https://developer.apple.com/design/resources/.
const Color _kDialogColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xCCF2F2F2),
  darkColor: Color(0xBF1E1E1E),
);
72

73
// Translucent light gray that is painted on top of the blurred backdrop as the
74
// background color of a pressed button.
75 76 77 78 79
// Eyeballed from iOS 13 beta simulator.
const Color _kDialogPressedColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xFFE1E1E1),
  darkColor: Color(0xFF2E2E2E),
);
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

// The alert dialog layout policy changes depending on whether the user is using
// a "regular" font size vs a "large" font size. This is a spectrum. There are
// many "regular" font sizes and many "large" font sizes. But depending on which
// policy is currently being used, a dialog is laid out differently.
//
// Empirically, the jump from one policy to the other occurs at the following text
// scale factors:
// Largest regular scale factor:  1.3529411764705883
// Smallest large scale factor:   1.6470588235294117
//
// The following constant represents a division in text scale factor beyond which
// we want to change how the dialog is laid out.
const double _kMaxRegularTextScaleFactor = 1.4;

// Accessibility mode on iOS is determined by the text scale factor that the
// user has selected.
bool _isInAccessibilityMode(BuildContext context) {
98
  final MediaQueryData? data = MediaQuery.of(context, nullOk: true);
99 100
  return data != null && data.textScaleFactor > _kMaxRegularTextScaleFactor;
}
101

102 103 104
/// An iOS-style alert dialog.
///
/// An alert dialog informs the user about situations that require
105 106 107 108 109 110 111 112 113 114 115
/// acknowledgement. An alert dialog has an optional title, optional content,
/// and an optional list of actions. The title is displayed above the content
/// and the actions are displayed below the content.
///
/// This dialog styles its title and content (typically a message) to match the
/// standard iOS title and message dialog text style. These default styles can
/// be overridden by explicitly defining [TextStyle]s for [Text] widgets that
/// are part of the title or content.
///
/// To display action buttons that look like standard iOS dialog buttons,
/// provide [CupertinoDialogAction]s for the [actions] given to this dialog.
116 117 118 119 120 121
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
/// See also:
///
122 123
///  * [CupertinoPopupSurface], which is a generic iOS-style popup surface that
///    holds arbitrary content to create custom popups.
124
///  * [CupertinoDialogAction], which is an iOS-style dialog button.
125
///  * [AlertDialog], a Material Design alert dialog.
126
///  * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>
127 128
class CupertinoAlertDialog extends StatelessWidget {
  /// Creates an iOS-style alert dialog.
129 130
  ///
  /// The [actions] must not be null.
131
  const CupertinoAlertDialog({
132
    Key? key,
133 134
    this.title,
    this.content,
135
    this.actions = const <Widget>[],
136
    this.scrollController,
137
    this.actionScrollController,
138 139
    this.insetAnimationDuration = const Duration(milliseconds: 100),
    this.insetAnimationCurve = Curves.decelerate,
140 141
  }) : assert(actions != null),
       super(key: key);
142 143 144 145 146

  /// The (optional) title of the dialog is displayed in a large font at the top
  /// of the dialog.
  ///
  /// Typically a [Text] widget.
147
  final Widget? title;
148 149 150 151 152

  /// The (optional) content of the dialog is displayed in the center of the
  /// dialog in a lighter font.
  ///
  /// Typically a [Text] widget.
153
  final Widget? content;
154 155 156 157 158 159 160

  /// The (optional) set of actions that are displayed at the bottom of the
  /// dialog.
  ///
  /// Typically this is a list of [CupertinoDialogAction] widgets.
  final List<Widget> actions;

161 162
  /// A scroll controller that can be used to control the scrolling of the
  /// [content] in the dialog.
163
  ///
164 165 166 167 168 169 170
  /// Defaults to null, and is typically not needed, since most alert messages
  /// are short.
  ///
  /// See also:
  ///
  ///  * [actionScrollController], which can be used for controlling the actions
  ///    section when there are many actions.
171
  final ScrollController? scrollController;
172

173 174 175 176 177 178 179 180 181
  /// A scroll controller that can be used to control the scrolling of the
  /// actions in the dialog.
  ///
  /// Defaults to null, and is typically not needed.
  ///
  /// See also:
  ///
  ///  * [scrollController], which can be used for controlling the [content]
  ///    section when it is long.
182
  final ScrollController? actionScrollController;
183

184 185 186 187 188 189
  /// {@macro flutter.material.dialog.insetAnimationDuration}
  final Duration insetAnimationDuration;

  /// {@macro flutter.material.dialog.insetAnimationCurve}
  final Curve insetAnimationCurve;

190
  Widget _buildContent(BuildContext context) {
191 192 193 194 195 196 197 198 199 200 201
    final List<Widget> children = <Widget>[
      if (title != null || content != null)
        Flexible(
          flex: 3,
          child: _CupertinoAlertContentSection(
            title: title,
            content: content,
            scrollController: scrollController,
          ),
        ),
    ];
202

203
    return Container(
204
      color: CupertinoDynamicColor.resolve(_kDialogColor, context),
205
      child: Column(
206 207 208 209 210 211 212 213
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: children,
      ),
    );
  }

  Widget _buildActions() {
214
    Widget actionSection = Container(
215 216
      height: 0.0,
    );
217
    if (actions.isNotEmpty) {
218
      actionSection = _CupertinoAlertActionSection(
219 220 221
        children: actions,
        scrollController: actionScrollController,
      );
222
    }
223

224 225 226 227 228
    return actionSection;
  }

  @override
  Widget build(BuildContext context) {
229
    final CupertinoLocalizations localizations = CupertinoLocalizations.of(context)!;
230
    final bool isInAccessibilityMode = _isInAccessibilityMode(context);
231
    final double textScaleFactor = MediaQuery.of(context)!.textScaleFactor;
232 233 234
    return CupertinoUserInterfaceLevel(
      data: CupertinoUserInterfaceLevelData.elevated,
      child: MediaQuery(
235
        data: MediaQuery.of(context)!.copyWith(
236 237 238 239 240
          // iOS does not shrink dialog content below a 1.0 scale factor
          textScaleFactor: math.max(textScaleFactor, 1.0),
        ),
        child: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
241
            return AnimatedPadding(
242
              padding: MediaQuery.of(context)!.viewInsets +
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                  const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
              duration: insetAnimationDuration,
              curve: insetAnimationCurve,
              child: MediaQuery.removeViewInsets(
                removeLeft: true,
                removeTop: true,
                removeRight: true,
                removeBottom: true,
                context: context,
                child: Center(
                  child: Container(
                    margin: const EdgeInsets.symmetric(vertical: _kEdgePadding),
                    width: isInAccessibilityMode
                      ? _kAccessibilityCupertinoDialogWidth
                      : _kCupertinoDialogWidth,
                    child: CupertinoPopupSurface(
                      isSurfacePainted: false,
                      child: Semantics(
                        namesRoute: true,
                        scopesRoute: true,
                        explicitChildNodes: true,
                        label: localizations.alertDialogLabel,
                        child: _CupertinoDialogRenderWidget(
                          contentSection: _buildContent(context),
                          actionsSection: _buildActions(),
                        ),
                      ),
270
                    ),
271
                  ),
272 273
                ),
              ),
274 275 276
            );
          },
        ),
277 278 279 280 281
      ),
    );
  }
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295
/// An iOS-style dialog.
///
/// This dialog widget does not have any opinion about the contents of the
/// dialog. Rather than using this widget directly, consider using
/// [CupertinoAlertDialog], which implement a specific kind of dialog.
///
/// Push with `Navigator.of(..., rootNavigator: true)` when using with
/// [CupertinoTabScaffold] to ensure that the dialog appears above the tabs.
///
/// See also:
///
///  * [CupertinoAlertDialog], which is a dialog with title, contents, and
///    actions.
///  * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>
296 297 298 299
@Deprecated(
  'Use CupertinoAlertDialog for alert dialogs. Use CupertinoPopupSurface for custom popups. '
  'This feature was deprecated after v0.2.3.'
)
300 301 302
class CupertinoDialog extends StatelessWidget {
  /// Creates an iOS-style dialog.
  const CupertinoDialog({
303
    Key? key,
304 305 306 307
    this.child,
  }) : super(key: key);

  /// The widget below this widget in the tree.
308
  final Widget? child;
309 310 311

  @override
  Widget build(BuildContext context) {
312 313
    return Center(
      child: SizedBox(
314
        width: _kCupertinoDialogWidth,
315
        child: CupertinoPopupSurface(
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
          child: child,
        ),
      ),
    );
  }
}

/// Rounded rectangle surface that looks like an iOS popup surface, e.g., alert dialog
/// and action sheet.
///
/// A [CupertinoPopupSurface] can be configured to paint or not paint a white
/// color on top of its blurred area. Typical usage should paint white on top
/// of the blur. However, the white paint can be disabled for the purpose of
/// rendering divider gaps for a more complicated layout, e.g., [CupertinoAlertDialog].
/// Additionally, the white paint can be disabled to render a blurred rounded
/// rectangle without any color (similar to iOS's volume control popup).
///
/// See also:
334
///
335 336 337 338 339 340
///  * [CupertinoAlertDialog], which is a dialog with a title, content, and
///    actions.
///  * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>
class CupertinoPopupSurface extends StatelessWidget {
  /// Creates an iOS-style rounded rectangle popup surface.
  const CupertinoPopupSurface({
341
    Key? key,
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    this.isSurfacePainted = true,
    this.child,
  }) : super(key: key);

  /// Whether or not to paint a translucent white on top of this surface's
  /// blurred background. [isSurfacePainted] should be true for a typical popup
  /// that contains content without any dividers. A popup that requires dividers
  /// should set [isSurfacePainted] to false and then paint its own surface area.
  ///
  /// Some popups, like iOS's volume control popup, choose to render a blurred
  /// area without any white paint covering it. To achieve this effect,
  /// [isSurfacePainted] should be set to false.
  final bool isSurfacePainted;

  /// The widget below this widget in the tree.
357
  final Widget? child;
358 359 360

  @override
  Widget build(BuildContext context) {
361
    return ClipRRect(
362
      borderRadius: BorderRadius.circular(_kDialogCornerRadius),
363 364 365
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount),
        child: Container(
366 367
          color: isSurfacePainted ? CupertinoDynamicColor.resolve(_kDialogColor, context) : null,
          child: child,
368 369 370 371 372 373
        ),
      ),
    );
  }
}

374 375 376 377 378 379
// iOS style layout policy widget for sizing an alert dialog's content section and
// action button section.
//
// See [_RenderCupertinoDialog] for specific layout policy details.
class _CupertinoDialogRenderWidget extends RenderObjectWidget {
  const _CupertinoDialogRenderWidget({
380 381 382
    Key? key,
    required this.contentSection,
    required this.actionsSection,
383
  }) : super(key: key);
384

385 386
  final Widget contentSection;
  final Widget actionsSection;
387

388 389
  @override
  RenderObject createRenderObject(BuildContext context) {
390
    return _RenderCupertinoDialog(
391
      dividerThickness: _kDividerThickness / MediaQuery.of(context)!.devicePixelRatio,
392
      isInAccessibilityMode: _isInAccessibilityMode(context),
393
      dividerColor: CupertinoDynamicColor.resolve(CupertinoColors.separator, context)!,
394 395
    );
  }
396

397 398
  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoDialog renderObject) {
399 400
    renderObject
      ..isInAccessibilityMode = _isInAccessibilityMode(context)
401
      ..dividerColor = CupertinoDynamicColor.resolve(CupertinoColors.separator, context)!;
402
  }
403

404 405 406 407 408
  @override
  RenderObjectElement createElement() {
    return _CupertinoDialogRenderElement(this);
  }
}
409

410 411 412
class _CupertinoDialogRenderElement extends RenderObjectElement {
  _CupertinoDialogRenderElement(_CupertinoDialogRenderWidget widget) : super(widget);

413 414
  Element? _contentElement;
  Element? _actionsElement;
415 416

  @override
417
  _CupertinoDialogRenderWidget get widget => super.widget as _CupertinoDialogRenderWidget;
418 419

  @override
420
  _RenderCupertinoDialog get renderObject => super.renderObject as _RenderCupertinoDialog;
421

422 423 424
  @override
  void visitChildren(ElementVisitor visitor) {
    if (_contentElement != null) {
425
      visitor(_contentElement!);
426
    }
427
    if (_actionsElement != null) {
428
      visitor(_actionsElement!);
429 430
    }
  }
431

432
  @override
433
  void mount(Element? parent, dynamic newSlot) {
434 435 436 437 438 439
    super.mount(parent, newSlot);
    _contentElement = updateChild(_contentElement, widget.contentSection, _AlertDialogSections.contentSection);
    _actionsElement = updateChild(_actionsElement, widget.actionsSection, _AlertDialogSections.actionsSection);
  }

  @override
440
  void insertRenderObjectChild(RenderObject child, _AlertDialogSections slot) {
441 442 443
    assert(slot != null);
    switch (slot) {
      case _AlertDialogSections.contentSection:
444
        renderObject.contentSection = child as RenderBox;
445 446
        break;
      case _AlertDialogSections.actionsSection:
447
        renderObject.actionsSection = child as RenderBox;
448
        break;
449
    }
450
  }
451

452
  @override
453
  void moveRenderObjectChild(RenderObject child, _AlertDialogSections oldSlot, _AlertDialogSections newSlot) {
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    assert(false);
  }

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

  @override
  void forgetChild(Element child) {
    assert(child == _contentElement || child == _actionsElement);
    if (_contentElement == child) {
      _contentElement = null;
    } else {
      assert(_actionsElement == child);
      _actionsElement = null;
472
    }
473
    super.forgetChild(child);
474
  }
475

476
  @override
477
  void removeRenderObjectChild(RenderObject child, _AlertDialogSections slot) {
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    assert(child == renderObject.contentSection || child == renderObject.actionsSection);
    if (renderObject.contentSection == child) {
      renderObject.contentSection = null;
    } else {
      assert(renderObject.actionsSection == child);
      renderObject.actionsSection = null;
    }
  }
}

// iOS style layout policy for sizing an alert dialog's content section and action
// button section.
//
// The policy is as follows:
//
// If all content and buttons fit on screen:
// The content section and action button section are sized intrinsically and centered
// vertically on screen.
//
// If all content and buttons do not fit on screen, and iOS is NOT in accessibility mode:
// A minimum height for the action button section is calculated. The action
// button section will not be rendered shorter than this minimum.  See
// [_RenderCupertinoDialogActions] for the minimum height calculation.
//
// With the minimum action button section calculated, the content section can
// take up as much space as is available, up to the point that it hits the
// minimum button height at the bottom.
//
// 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.
//
// If all content and buttons do not fit on screen, and iOS IS in accessibility mode:
// The button section is given up to 50% of the available height. Then the content
// section is given whatever height remains.
class _RenderCupertinoDialog extends RenderBox {
  _RenderCupertinoDialog({
514 515
    RenderBox? contentSection,
    RenderBox? actionsSection,
516 517
    double dividerThickness = 0.0,
    bool isInAccessibilityMode = false,
518
    required Color dividerColor,
519 520 521
  }) : _contentSection = contentSection,
       _actionsSection = actionsSection,
       _dividerThickness = dividerThickness,
522 523 524 525 526
       _isInAccessibilityMode = isInAccessibilityMode,
       _dividerPaint = Paint()
        ..color = dividerColor
        ..style = PaintingStyle.fill;

527

528 529 530
  RenderBox? get contentSection => _contentSection;
  RenderBox? _contentSection;
  set contentSection(RenderBox? newContentSection) {
531 532
    if (newContentSection != _contentSection) {
      if (_contentSection != null) {
533
        dropChild(_contentSection!);
534 535 536
      }
      _contentSection = newContentSection;
      if (_contentSection != null) {
537
        adoptChild(_contentSection!);
538 539 540 541
      }
    }
  }

542 543 544
  RenderBox? get actionsSection => _actionsSection;
  RenderBox? _actionsSection;
  set actionsSection(RenderBox? newActionsSection) {
545 546
    if (newActionsSection != _actionsSection) {
      if (null != _actionsSection) {
547
        dropChild(_actionsSection!);
548 549 550
      }
      _actionsSection = newActionsSection;
      if (null != _actionsSection) {
551
        adoptChild(_actionsSection!);
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
      }
    }
  }

  bool get isInAccessibilityMode => _isInAccessibilityMode;
  bool _isInAccessibilityMode;
  set isInAccessibilityMode(bool newValue) {
    if (newValue != _isInAccessibilityMode) {
      _isInAccessibilityMode = newValue;
      markNeedsLayout();
    }
  }

  double get _dialogWidth => isInAccessibilityMode
      ? _kAccessibilityCupertinoDialogWidth
      : _kCupertinoDialogWidth;

  final double _dividerThickness;
570 571 572 573 574 575 576
  final Paint _dividerPaint;

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

578 579 580
    _dividerPaint.color = newValue;
    markNeedsPaint();
  }
581 582 583 584 585

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    if (null != contentSection) {
586
      contentSection!.attach(owner);
587 588
    }
    if (null != actionsSection) {
589
      actionsSection!.attach(owner);
590 591 592 593 594 595 596
    }
  }

  @override
  void detach() {
    super.detach();
    if (null != contentSection) {
597
      contentSection!.detach();
598 599
    }
    if (null != actionsSection) {
600
      actionsSection!.detach();
601 602 603 604 605 606
    }
  }

  @override
  void redepthChildren() {
    if (null != contentSection) {
607
      redepthChild(contentSection!);
608 609
    }
    if (null != actionsSection) {
610
      redepthChild(actionsSection!);
611 612 613 614 615 616
    }
  }

  @override
  void setupParentData(RenderBox child) {
    if (child.parentData is! BoxParentData) {
617
      child.parentData = BoxParentData();
618 619 620 621 622 623
    }
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    if (contentSection != null) {
624
      visitor(contentSection!);
625 626
    }
    if (actionsSection != null) {
627
      visitor(actionsSection!);
628 629 630 631
    }
  }

  @override
632
  List<DiagnosticsNode> debugDescribeChildren() => <DiagnosticsNode>[
633 634
    if (contentSection != null) contentSection!.toDiagnosticsNode(name: 'content'),
    if (actionsSection != null) actionsSection!.toDiagnosticsNode(name: 'actions'),
635
  ];
636 637 638 639 640 641 642 643 644 645 646 647 648

  @override
  double computeMinIntrinsicWidth(double height) {
    return _dialogWidth;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    return _dialogWidth;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
649 650
    final double contentHeight = contentSection!.getMinIntrinsicHeight(width);
    final double actionsHeight = actionsSection!.getMinIntrinsicHeight(width);
651 652 653 654 655 656 657 658 659 660
    final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0;
    final double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight;

    if (height.isFinite)
      return height;
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
661 662
    final double contentHeight = contentSection!.getMaxIntrinsicHeight(width);
    final double actionsHeight = actionsSection!.getMaxIntrinsicHeight(width);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0;
    final double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight;

    if (height.isFinite)
      return height;
    return 0.0;
  }

  @override
  void performLayout() {
    if (isInAccessibilityMode) {
      // When in accessibility mode, an alert dialog will allow buttons to take
      // up to 50% of the dialog height, even if the content exceeds available space.
      performAccessibilityLayout();
    } else {
      // When not in accessibility mode, an alert dialog might reduce the space
      // for buttons to just over 1 button's height to make room for the content
      // section.
      performRegularLayout();
    }
  }

  void performRegularLayout() {
686 687
    final bool hasDivider = contentSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0
        && actionsSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0;
688 689
    final double dividerThickness = hasDivider ? _dividerThickness : 0.0;

690
    final double minActionsHeight = actionsSection!.getMinIntrinsicHeight(_dialogWidth);
691 692

    // Size alert dialog content.
693
    contentSection!.layout(
694
      constraints.deflate(EdgeInsets.only(bottom: minActionsHeight + dividerThickness)),
695 696
      parentUsesSize: true,
    );
697
    final Size contentSize = contentSection!.size;
698 699

    // Size alert dialog actions.
700
    actionsSection!.layout(
701
      constraints.deflate(EdgeInsets.only(top: contentSize.height + dividerThickness)),
702 703
      parentUsesSize: true,
    );
704
    final Size actionsSize = actionsSection!.size;
705 706 707 708 709 710

    // Calculate overall dialog height.
    final double dialogHeight = contentSize.height + dividerThickness + actionsSize.height;

    // Set our size now that layout calculations are complete.
    size = constraints.constrain(
711
      Size(_dialogWidth, dialogHeight)
712 713 714 715
    );

    // Set the position of the actions box to sit at the bottom of the dialog.
    // The content box defaults to the top left, which is where we want it.
716
    assert(actionsSection!.parentData is BoxParentData);
717
    final BoxParentData actionParentData = actionsSection!.parentData! as BoxParentData;
718
    actionParentData.offset = Offset(0.0, contentSize.height + dividerThickness);
719 720 721
  }

  void performAccessibilityLayout() {
722 723
    final bool hasDivider = contentSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0
        && actionsSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0;
724 725
    final double dividerThickness = hasDivider ? _dividerThickness : 0.0;

726 727
    final double maxContentHeight = contentSection!.getMaxIntrinsicHeight(_dialogWidth);
    final double maxActionsHeight = actionsSection!.getMaxIntrinsicHeight(_dialogWidth);
728 729 730 731 732 733 734 735 736 737

    Size contentSize;
    Size actionsSize;
    if (maxContentHeight + dividerThickness + maxActionsHeight > constraints.maxHeight) {
      // There isn't enough room for everything. Following iOS's accessibility dialog
      // layout policy, first we allow the actions to take up to 50% of the dialog
      // height. Second we fill the rest of the available space with the content
      // section.

      // Size alert dialog actions.
738
      actionsSection!.layout(
739
        constraints.deflate(EdgeInsets.only(top: constraints.maxHeight / 2.0)),
740 741
        parentUsesSize: true,
      );
742
      actionsSize = actionsSection!.size;
743 744

      // Size alert dialog content.
745
      contentSection!.layout(
746
        constraints.deflate(EdgeInsets.only(bottom: actionsSize.height + dividerThickness)),
747 748
        parentUsesSize: true,
      );
749
      contentSize = contentSection!.size;
750 751 752 753
    } else {
      // Everything fits. Give content and actions all the space they want.

      // Size alert dialog content.
754
      contentSection!.layout(
755 756 757
        constraints,
        parentUsesSize: true,
      );
758
      contentSize = contentSection!.size;
759 760

      // Size alert dialog actions.
761
      actionsSection!.layout(
762
        constraints.deflate(EdgeInsets.only(top: contentSize.height)),
763 764
        parentUsesSize: true,
      );
765
      actionsSize = actionsSection!.size;
766 767 768 769 770 771 772
    }

    // Calculate overall dialog height.
    final double dialogHeight = contentSize.height + dividerThickness + actionsSize.height;

    // Set our size now that layout calculations are complete.
    size = constraints.constrain(
773
      Size(_dialogWidth, dialogHeight)
774 775 776 777
    );

    // Set the position of the actions box to sit at the bottom of the dialog.
    // The content box defaults to the top left, which is where we want it.
778
    assert(actionsSection!.parentData is BoxParentData);
779
    final BoxParentData actionParentData = actionsSection!.parentData! as BoxParentData;
780
    actionParentData.offset = Offset(0.0, contentSize.height + dividerThickness);
781 782 783 784
  }

  @override
  void paint(PaintingContext context, Offset offset) {
785
    final BoxParentData contentParentData = contentSection!.parentData! as BoxParentData;
786
    contentSection!.paint(context, offset + contentParentData.offset);
787

788
    final bool hasDivider = contentSection!.size.height > 0.0 && actionsSection!.size.height > 0.0;
789 790 791 792
    if (hasDivider) {
      _paintDividerBetweenContentAndActions(context.canvas, offset);
    }

793
    final BoxParentData actionsParentData = actionsSection!.parentData! as BoxParentData;
794
    actionsSection!.paint(context, offset + actionsParentData.offset);
795 796 797 798 799 800
  }

  void _paintDividerBetweenContentAndActions(Canvas canvas, Offset offset) {
    canvas.drawRect(
      Rect.fromLTWH(
        offset.dx,
801
        offset.dy + contentSection!.size.height,
802 803
        size.width,
        _dividerThickness,
804
      ),
805
      _dividerPaint,
806 807
    );
  }
808 809

  @override
810
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
811 812
    final BoxParentData contentSectionParentData = contentSection!.parentData! as BoxParentData;
    final BoxParentData actionsSectionParentData = actionsSection!.parentData! as BoxParentData;
813 814 815 816 817
    return result.addWithPaintOffset(
             offset: contentSectionParentData.offset,
             position: position,
             hitTest: (BoxHitTestResult result, Offset transformed) {
               assert(transformed == position - contentSectionParentData.offset);
818
               return contentSection!.hitTest(result, position: transformed);
819 820 821 822 823 824 825
             },
           )
        || result.addWithPaintOffset(
             offset: actionsSectionParentData.offset,
             position: position,
             hitTest: (BoxHitTestResult result, Offset transformed) {
               assert(transformed == position - actionsSectionParentData.offset);
826
               return actionsSection!.hitTest(result, position: transformed);
827 828
             },
           );
829
  }
830 831
}

832 833 834 835 836 837 838 839
// Visual components of an alert dialog that need to be explicitly sized and
// laid out at runtime.
enum _AlertDialogSections {
  contentSection,
  actionsSection,
}

// The "content section" of a CupertinoAlertDialog.
840 841 842 843
//
// If title is missing, then only content is added.  If content is
// missing, then only title is added. If both are missing, then it returns
// a SingleChildScrollView with a zero-sized Container.
844 845
class _CupertinoAlertContentSection extends StatelessWidget {
  const _CupertinoAlertContentSection({
846
    Key? key,
847 848 849
    this.title,
    this.content,
    this.scrollController,
850 851
  }) : super(key: key);

852 853 854 855
  // The (optional) title of the dialog is displayed in a large font at the top
  // of the dialog.
  //
  // Typically a Text widget.
856
  final Widget? title;
857 858 859 860 861

  // The (optional) content of the dialog is displayed in the center of the
  // dialog in a lighter font.
  //
  // Typically a Text widget.
862
  final Widget? content;
863 864 865 866 867 868

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

  @override
  Widget build(BuildContext context) {
873 874 875
    if (title == null && content == null) {
      return SingleChildScrollView(
        controller: scrollController,
876
        child: const SizedBox(width: 0.0, height: 0.0),
877
      );
878 879
    }

880
    final double textScaleFactor = MediaQuery.of(context)!.textScaleFactor;
881 882 883 884 885 886 887 888 889 890 891
    final List<Widget> titleContentGroup = <Widget>[
      if (title != null)
        Padding(
          padding: EdgeInsets.only(
            left: _kEdgePadding,
            right: _kEdgePadding,
            bottom: content == null ? _kEdgePadding : 1.0,
            top: _kEdgePadding * textScaleFactor,
          ),
          child: DefaultTextStyle(
            style: _kCupertinoDialogTitleStyle.copyWith(
892
              color: CupertinoDynamicColor.resolve(CupertinoColors.label, context),
893 894
            ),
            textAlign: TextAlign.center,
895
            child: title!,
896 897 898
          ),
        ),
      if (content != null)
899 900
        Padding(
          padding: EdgeInsets.only(
901 902
            left: _kEdgePadding,
            right: _kEdgePadding,
903
            bottom: _kEdgePadding * textScaleFactor,
904 905
            top: title == null ? _kEdgePadding : 1.0,
          ),
906
          child: DefaultTextStyle(
907
            style: _kCupertinoDialogContentStyle.copyWith(
908
              color: CupertinoDynamicColor.resolve(CupertinoColors.label, context),
909
            ),
910
            textAlign: TextAlign.center,
911
            child: content!,
912 913
          ),
        ),
914
    ];
915

916 917
    return CupertinoScrollbar(
      child: SingleChildScrollView(
918
        controller: scrollController,
919
        child: Column(
920 921 922
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: titleContentGroup,
923
        ),
924
      ),
925 926 927 928
    );
  }
}

929
// The "actions section" of a [CupertinoAlertDialog].
930
//
931 932 933
// See [_RenderCupertinoDialogActions] for details about action button sizing
// and layout.
class _CupertinoAlertActionSection extends StatefulWidget {
934
  const _CupertinoAlertActionSection({
935 936
    Key? key,
    required this.children,
937
    this.scrollController,
938 939
  }) : assert(children != null),
       super(key: key);
940 941 942 943 944 945 946 947

  final List<Widget> children;

  // A scroll controller that can be used to control the scrolling of the
  // actions in the dialog.
  //
  // Defaults to null, and is typically not needed, since most alert dialogs
  // don't have many actions.
948
  final ScrollController? scrollController;
949

950
  @override
951
  _CupertinoAlertActionSectionState createState() => _CupertinoAlertActionSectionState();
952
}
953

954
class _CupertinoAlertActionSectionState extends State<_CupertinoAlertActionSection> {
955 956
  @override
  Widget build(BuildContext context) {
957
    final double devicePixelRatio = MediaQuery.of(context)!.devicePixelRatio;
958

959 960 961
    final List<Widget> interactiveButtons = <Widget>[];
    for (int i = 0; i < widget.children.length; i += 1) {
      interactiveButtons.add(
962
        _PressableActionButton(
963
          child: widget.children[i],
964 965
        ),
      );
966
    }
967

968 969
    return CupertinoScrollbar(
      child: SingleChildScrollView(
970
        controller: widget.scrollController,
971
        child: _CupertinoDialogActionsRenderWidget(
972 973
          actionButtons: interactiveButtons,
          dividerThickness: _kDividerThickness / devicePixelRatio,
974
        ),
975 976 977 978 979 980 981 982 983 984 985 986
      ),
    );
  }
}

// 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 _RenderCupertinoDialogActions.
class _PressableActionButton extends StatefulWidget {
  const _PressableActionButton({
987
    required this.child,
988 989 990 991 992
  });

  final Widget child;

  @override
993
  _PressableActionButtonState createState() => _PressableActionButtonState();
994 995 996 997 998 999 1000
}

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

  @override
  Widget build(BuildContext context) {
1001
    return _ActionButtonParentDataWidget(
1002
      isPressed: _isPressed,
1003
      child: MergeSemantics(
1004 1005
        // TODO(mattcarroll): Button press dynamics need overhaul for iOS:
        // https://github.com/flutter/flutter/issues/19786
1006
        child: GestureDetector(
1007 1008 1009 1010 1011 1012 1013 1014
          excludeFromSemantics: true,
          behavior: HitTestBehavior.opaque,
          onTapDown: (TapDownDetails details) => setState(() {
            _isPressed = true;
          }),
          onTapUp: (TapUpDetails details) => setState(() {
            _isPressed = false;
          }),
1015 1016
          // TODO(mattcarroll): Cancel is currently triggered when user moves
          //  past slop instead of off button: https://github.com/flutter/flutter/issues/19783
1017 1018 1019
          onTapCancel: () => setState(() => _isPressed = false),
          child: widget.child,
        ),
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
      ),
    );
  }
}

// ParentDataWidget that updates _ActionButtonParentData for an action button.
//
// Each action button requires knowledge of whether or not it is pressed so that
// the dialog 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.
1032
class _ActionButtonParentDataWidget extends ParentDataWidget<_ActionButtonParentData> {
1033
  const _ActionButtonParentDataWidget({
1034 1035 1036
    Key? key,
    required this.isPressed,
    required Widget child,
1037 1038 1039 1040 1041 1042 1043
  }) : super(key: key, child: child);

  final bool isPressed;

  @override
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is _ActionButtonParentData);
1044
    final _ActionButtonParentData parentData = renderObject.parentData! as _ActionButtonParentData;
1045 1046 1047 1048
    if (parentData.isPressed != isPressed) {
      parentData.isPressed = isPressed;

      // Force a repaint.
1049
      final AbstractNode? targetParent = renderObject.parent;
1050 1051 1052 1053
      if (targetParent is RenderObject)
        targetParent.markNeedsPaint();
    }
  }
1054 1055 1056

  @override
  Type get debugTypicalAncestorWidgetClass => _CupertinoDialogActionsRenderWidget;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
}

// 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;
}

/// A button typically used in a [CupertinoAlertDialog].
///
/// See also:
///
///  * [CupertinoAlertDialog], a dialog that informs the user about situations
1074
///    that require acknowledgement.
1075 1076 1077
class CupertinoDialogAction extends StatelessWidget {
  /// Creates an action for an iOS-style dialog.
  const CupertinoDialogAction({
1078
    Key? key,
1079 1080 1081 1082
    this.onPressed,
    this.isDefaultAction = false,
    this.isDestructiveAction = false,
    this.textStyle,
1083
    required this.child,
1084 1085
  }) : assert(child != null),
       assert(isDefaultAction != null),
1086 1087
       assert(isDestructiveAction != null),
       super(key: key);
1088 1089 1090 1091 1092

  /// The callback that is called when the button is tapped or otherwise
  /// activated.
  ///
  /// If this is set to null, the button will be disabled.
1093
  final VoidCallback? onPressed;
1094 1095 1096

  /// Set to true if button is the default choice in the dialog.
  ///
1097 1098 1099 1100
  /// Default buttons have bold text. Similar to
  /// [UIAlertController.preferredAction](https://developer.apple.com/documentation/uikit/uialertcontroller/1620102-preferredaction),
  /// but more than one action can have this attribute set to true in the same
  /// [CupertinoAlertDialog].
1101 1102
  ///
  /// This parameters defaults to false and cannot be null.
1103 1104 1105 1106 1107
  final bool isDefaultAction;

  /// Whether this action destroys an object.
  ///
  /// For example, an action that deletes an email is destructive.
1108 1109
  ///
  /// Defaults to false and cannot be null.
1110 1111 1112 1113 1114 1115 1116 1117
  final bool isDestructiveAction;

  /// [TextStyle] to apply to any text that appears in this button.
  ///
  /// Dialog actions have a built-in text resizing policy for long text. To
  /// ensure that this resizing policy always works as expected, [textStyle]
  /// must be used if a text size is desired other than that specified in
  /// [_kCupertinoDialogActionStyle].
1118
  final TextStyle? textStyle;
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

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

  /// Whether the button is enabled or disabled. Buttons are disabled by
  /// default. To enable a button, set its [onPressed] property to a non-null
  /// value.
  bool get enabled => onPressed != null;

  double _calculatePadding(BuildContext context) {
    return 8.0 * MediaQuery.textScaleFactorOf(context);
  }

  // Dialog action content shrinks to fit, up to a certain point, and if it still
  // cannot fit at the minimum size, the text content is ellipsized.
  //
  // This policy only applies when the device is not in accessibility mode.
  Widget _buildContentWithRegularSizingPolicy({
1139 1140 1141
    required BuildContext context,
    required TextStyle textStyle,
    required Widget content,
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  }) {
    final bool isInAccessibilityMode = _isInAccessibilityMode(context);
    final double dialogWidth = isInAccessibilityMode
        ? _kAccessibilityCupertinoDialogWidth
        : _kCupertinoDialogWidth;
    final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
    // The fontSizeRatio is the ratio of the current text size (including any
    // iOS scale factor) vs the minimum text size that we allow in action
    // buttons. This ratio information is used to automatically scale down action
    // button text to fit the available space.
1152
    final double fontSizeRatio = (textScaleFactor * textStyle.fontSize!) / _kMinButtonFontSize;
1153 1154
    final double padding = _calculatePadding(context);

1155 1156
    return IntrinsicHeight(
      child: SizedBox(
1157
        width: double.infinity,
1158
        child: FittedBox(
1159
          fit: BoxFit.scaleDown,
1160 1161
          child: ConstrainedBox(
            constraints: BoxConstraints(
1162 1163
              maxWidth: fontSizeRatio * (dialogWidth - (2 * padding)),
            ),
1164
            child: Semantics(
1165 1166
              button: true,
              onTap: onPressed,
1167
              child: DefaultTextStyle(
1168 1169 1170 1171 1172 1173
                style: textStyle,
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                child: content,
              ),
1174 1175 1176
            ),
          ),
        ),
1177 1178 1179 1180 1181 1182 1183 1184
      ),
    );
  }

  // Dialog action content is permitted to be as large as it wants when in
  // accessibility mode. If text is used as the content, the text wraps instead
  // of ellipsizing.
  Widget _buildContentWithAccessibilitySizingPolicy({
1185 1186
    required TextStyle textStyle,
    required Widget content,
1187
  }) {
1188
    return DefaultTextStyle(
1189 1190 1191 1192 1193 1194 1195 1196
      style: textStyle,
      textAlign: TextAlign.center,
      child: content,
    );
  }

  @override
  Widget build(BuildContext context) {
1197 1198
    TextStyle style = _kCupertinoDialogActionStyle.copyWith(
      color: CupertinoDynamicColor.resolve(
1199
        isDestructiveAction ?  CupertinoColors.systemRed : CupertinoColors.systemBlue,
1200
        context,
1201 1202
      ),
    );
1203 1204
    style = style.merge(textStyle);

1205 1206 1207 1208
    if (isDefaultAction) {
      style = style.copyWith(fontWeight: FontWeight.w600);
    }

1209
    if (!enabled) {
1210
      style = style.copyWith(color: style.color!.withOpacity(0.5));
1211
    }
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

    // Apply a sizing policy to the action button's content based on whether or
    // not the device is in accessibility mode.
    // TODO(mattcarroll): The following logic is not entirely correct. It is also
    // the case that if content text does not contain a space, it should also
    // wrap instead of ellipsizing. We are consciously not implementing that
    // now due to complexity.
    final Widget sizedContent = _isInAccessibilityMode(context)
      ? _buildContentWithAccessibilitySizingPolicy(
          textStyle: style,
          content: child,
        )
      : _buildContentWithRegularSizingPolicy(
          context: context,
          textStyle: style,
          content: child,
        );

1230
    return GestureDetector(
1231
      excludeFromSemantics: true,
1232 1233
      onTap: onPressed,
      behavior: HitTestBehavior.opaque,
1234
      child: ConstrainedBox(
1235 1236 1237
        constraints: const BoxConstraints(
          minHeight: _kMinButtonHeight,
        ),
1238
        child: Container(
1239
          alignment: Alignment.center,
1240
          padding: EdgeInsets.all(_calculatePadding(context)),
1241 1242 1243 1244
          child: sizedContent,
        ),
      ),
    );
1245 1246 1247
  }
}

1248
// iOS style dialog action button layout.
1249
//
1250 1251 1252 1253 1254 1255 1256
// [_CupertinoDialogActionsRenderWidget] does not provide any scrolling
// behavior for its buttons. It only handles the sizing and layout of buttons.
// Scrolling behavior can be composed on top of this widget, if desired.
//
// See [_RenderCupertinoDialogActions] for specific layout policy details.
class _CupertinoDialogActionsRenderWidget extends MultiChildRenderObjectWidget {
  _CupertinoDialogActionsRenderWidget({
1257 1258
    Key? key,
    required List<Widget> actionButtons,
1259 1260 1261
    double dividerThickness = 0.0,
  }) : _dividerThickness = dividerThickness,
       super(key: key, children: actionButtons);
1262

1263
  final double _dividerThickness;
1264 1265

  @override
1266
  RenderObject createRenderObject(BuildContext context) {
1267
    return _RenderCupertinoDialogActions(
1268 1269 1270 1271
      dialogWidth: _isInAccessibilityMode(context)
        ? _kAccessibilityCupertinoDialogWidth
        : _kCupertinoDialogWidth,
      dividerThickness: _dividerThickness,
1272 1273 1274
      dialogColor: CupertinoDynamicColor.resolve(_kDialogColor, context)!,
      dialogPressedColor: CupertinoDynamicColor.resolve(_kDialogPressedColor, context)!,
      dividerColor: CupertinoDynamicColor.resolve(CupertinoColors.separator, context)!,
1275
    );
1276 1277 1278
  }

  @override
1279
  void updateRenderObject(BuildContext context, _RenderCupertinoDialogActions renderObject) {
1280 1281 1282 1283 1284
    renderObject
      ..dialogWidth = _isInAccessibilityMode(context)
        ? _kAccessibilityCupertinoDialogWidth
        : _kCupertinoDialogWidth
      ..dividerThickness = _dividerThickness
1285 1286 1287
      ..dialogColor = CupertinoDynamicColor.resolve(_kDialogColor, context)!
      ..dialogPressedColor = CupertinoDynamicColor.resolve(_kDialogPressedColor, context)!
      ..dividerColor = CupertinoDynamicColor.resolve(CupertinoColors.separator, context)!;
1288
  }
1289 1290
}

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
// iOS style layout policy for sizing and positioning an alert dialog's action
// buttons.
//
// The policy is as follows:
//
// If a single action button is provided, or if 2 action buttons are provided
// that can fit side-by-side, then action buttons are sized and laid out in a
// single horizontal row. The row is exactly as wide as the dialog, and the row
// is as tall as the tallest action button. A horizontal divider is drawn above
// the button row. If 2 action buttons are provided, a vertical divider is
// drawn between them. The thickness of the divider is set by [dividerThickness].
//
// If 2 action buttons are provided but they cannot fit side-by-side, then the
// 2 buttons are stacked vertically. A horizontal divider is drawn above each
// button. The thickness of the divider is set by [dividerThickness]. The minimum
// height of this [RenderBox] in the case of 2 stacked buttons is as tall as
// the 2 buttons stacked. This is different than the 3+ button case where the
// minimum height is only 1.5 buttons tall. See the 3+ button explanation for
// more info.
1310
//
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
// If 3+ action buttons are provided then they are all stacked vertically. A
// horizontal divider is drawn above each button. The thickness of the divider
// is set by [dividerThickness]. The minimum height of this [RenderBox] in the case
// of 3+ stacked buttons is as tall as the 1st button + 50% the height of the
// 2nd button. In other words, the minimum height is 1.5 buttons tall. This
// minimum height of 1.5 buttons is expected to work in tandem with a surrounding
// [ScrollView] to match the iOS dialog behavior.
//
// Each button is expected to have an _ActionButtonParentData which reports
// whether or not that button is currently pressed. If a button is pressed,
// then the dividers above and below that pressed button are not drawn - instead
// they are filled with the standard white dialog background color. The one
// exception is the very 1st divider which is always rendered. This policy comes
// from observation of native iOS dialogs.
class _RenderCupertinoDialogActions extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, MultiChildLayoutParentData>,
        RenderBoxContainerDefaultsMixin<RenderBox, MultiChildLayoutParentData> {
  _RenderCupertinoDialogActions({
1329 1330
    List<RenderBox>? children,
    required double dialogWidth,
1331
    double dividerThickness = 0.0,
1332 1333 1334
    required Color dialogColor,
    required Color dialogPressedColor,
    required Color dividerColor,
1335
  }) : _dialogWidth = dialogWidth,
1336 1337 1338 1339 1340 1341 1342 1343 1344
       _buttonBackgroundPaint = Paint()
        ..color = dialogColor
        ..style = PaintingStyle.fill,
        _pressedButtonBackgroundPaint = Paint()
          ..color = dialogPressedColor
          ..style = PaintingStyle.fill,
        _dividerPaint = Paint()
          ..color = dividerColor
          ..style = PaintingStyle.fill,
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
       _dividerThickness = dividerThickness {
    addAll(children);
  }

  double get dialogWidth => _dialogWidth;
  double _dialogWidth;
  set dialogWidth(double newWidth) {
    if (newWidth != _dialogWidth) {
      _dialogWidth = newWidth;
      markNeedsLayout();
    }
  }

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

1368 1369 1370 1371 1372 1373 1374 1375
  final Paint _buttonBackgroundPaint;
  set dialogColor(Color value) {
    if (value == _buttonBackgroundPaint.color)
      return;

    _buttonBackgroundPaint.color = value;
    markNeedsPaint();
  }
1376

1377 1378 1379
  final Paint _pressedButtonBackgroundPaint;
  set dialogPressedColor(Color value) {
    if (value == _pressedButtonBackgroundPaint.color)
1380
      return;
1381

1382 1383 1384 1385 1386 1387 1388
    _pressedButtonBackgroundPaint.color = value;
    markNeedsPaint();
  }

  final Paint _dividerPaint;
  set dividerColor(Color value) {
    if (value == _dividerPaint.color)
1389
      return;
1390 1391 1392 1393

    _dividerPaint.color = value;
    markNeedsPaint();
  }
1394 1395

  Iterable<RenderBox> get _pressedButtons sync* {
1396
    RenderBox? currentChild = firstChild;
1397 1398
    while (currentChild != null) {
      assert(currentChild.parentData is _ActionButtonParentData);
1399
      final _ActionButtonParentData parentData = currentChild.parentData! as _ActionButtonParentData;
1400 1401 1402 1403 1404 1405 1406 1407
      if (parentData.isPressed) {
        yield currentChild;
      }
      currentChild = childAfter(currentChild);
    }
  }

  bool get _isButtonPressed {
1408
    RenderBox? currentChild = firstChild;
1409 1410
    while (currentChild != null) {
      assert(currentChild.parentData is _ActionButtonParentData);
1411
      final _ActionButtonParentData parentData = currentChild.parentData! as _ActionButtonParentData;
1412 1413 1414 1415 1416 1417 1418
      if (parentData.isPressed) {
        return true;
      }
      currentChild = childAfter(currentChild);
    }
    return false;
  }
1419 1420

  @override
1421 1422
  void setupParentData(RenderBox child) {
    if (child.parentData is! _ActionButtonParentData)
1423
      child.parentData = _ActionButtonParentData();
1424 1425 1426
  }

  @override
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
  double computeMinIntrinsicWidth(double height) {
    return dialogWidth;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    return dialogWidth;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    double minHeight;
    if (childCount == 0) {
      minHeight = 0.0;
    } else if (childCount == 1) {
      // If only 1 button, display the button across the entire dialog.
      minHeight = _computeMinIntrinsicHeightSideBySide(width);
    } else {
      if (childCount == 2 && _isSingleButtonRow(width)) {
        // The first 2 buttons fit side-by-side. Display them horizontally.
        minHeight = _computeMinIntrinsicHeightSideBySide(width);
      } else {
        // 3+ buttons are always stacked. The minimum height when stacked is
        // 1.5 buttons tall.
        minHeight = _computeMinIntrinsicHeightStacked(width);
      }
    }
    return minHeight;
  }

  // The minimum height for a single row of buttons is the larger of the buttons'
  // min intrinsic heights.
  double _computeMinIntrinsicHeightSideBySide(double width) {
    assert(childCount >= 1 && childCount <= 2);

    double minHeight;
    if (childCount == 1) {
1464
      minHeight = firstChild!.getMinIntrinsicHeight(width);
1465 1466 1467
    } else {
      final double perButtonWidth = (width - dividerThickness) / 2.0;
      minHeight = math.max(
1468 1469
        firstChild!.getMinIntrinsicHeight(perButtonWidth),
        lastChild!.getMinIntrinsicHeight(perButtonWidth),
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
      );
    }
    return minHeight;
  }

  // The minimum height for 2+ stacked buttons is the height of the 1st button
  // + 50% the height of the 2nd button + the divider between the two.
  double _computeMinIntrinsicHeightStacked(double width) {
    assert(childCount >= 2);

1480
    return firstChild!.getMinIntrinsicHeight(width)
1481
      + dividerThickness
1482
      + (0.5 * childAfter(firstChild!)!.getMinIntrinsicHeight(width));
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    double maxHeight;
    if (childCount == 0) {
      // No buttons. Zero height.
      maxHeight = 0.0;
    } else if (childCount == 1) {
      // One button. Our max intrinsic height is equal to the button's.
1493
      maxHeight = firstChild!.getMaxIntrinsicHeight(width);
1494 1495 1496 1497 1498 1499 1500
    } else if (childCount == 2) {
      // Two buttons...
      if (_isSingleButtonRow(width)) {
        // The 2 buttons fit side by side so our max intrinsic height is equal
        // to the taller of the 2 buttons.
        final double perButtonWidth = (width - dividerThickness) / 2.0;
        maxHeight = math.max(
1501 1502
          firstChild!.getMaxIntrinsicHeight(perButtonWidth),
          lastChild!.getMaxIntrinsicHeight(perButtonWidth),
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
        );
      } else {
        // The 2 buttons do not fit side by side. Measure total height as a
        // vertical stack.
        maxHeight = _computeMaxIntrinsicHeightStacked(width);
      }
    } else {
      // Three+ buttons. Stack the buttons vertically with dividers and measure
      // the overall height.
      maxHeight = _computeMaxIntrinsicHeightStacked(width);
    }
    return maxHeight;
  }

  // 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;
1524
    RenderBox? button = firstChild;
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    while (button != null) {
      heightAccumulation += button.getMaxIntrinsicHeight(width);
      button = childAfter(button);
    }
    return heightAccumulation;
  }

  bool _isSingleButtonRow(double width) {
    bool isSingleButtonRow;
    if (childCount == 1) {
      isSingleButtonRow = true;
    } else if (childCount == 2) {
      // There are 2 buttons. If they can fit side-by-side then that's what
      // we want to do. Otherwise, stack them vertically.
1539
      final double sideBySideWidth = firstChild!.getMaxIntrinsicWidth(double.infinity)
1540
          + dividerThickness
1541
          + lastChild!.getMaxIntrinsicWidth(double.infinity);
1542 1543 1544 1545 1546 1547 1548 1549 1550
      isSingleButtonRow = sideBySideWidth <= width;
    } else {
      isSingleButtonRow = false;
    }
    return isSingleButtonRow;
  }

  @override
  void performLayout() {
1551
    final BoxConstraints constraints = this.constraints;
1552 1553 1554 1555
    if (_isSingleButtonRow(dialogWidth)) {
      if (childCount == 1) {
        // We have 1 button. Our size is the width of the dialog and the height
        // of the single button.
1556
        firstChild!.layout(
1557 1558 1559 1560 1561
          constraints,
          parentUsesSize: true,
        );

        size = constraints.constrain(
1562
          Size(dialogWidth, firstChild!.size.height)
1563 1564 1565
        );
      } else {
        // Each button gets half the available width, minus a single divider.
1566
        final BoxConstraints perButtonConstraints = BoxConstraints(
1567 1568 1569 1570 1571 1572 1573
          minWidth: (constraints.minWidth - dividerThickness) / 2.0,
          maxWidth: (constraints.maxWidth - dividerThickness) / 2.0,
          minHeight: 0.0,
          maxHeight: double.infinity,
        );

        // Layout the 2 buttons.
1574
        firstChild!.layout(
1575 1576 1577
          perButtonConstraints,
          parentUsesSize: true,
        );
1578
        lastChild!.layout(
1579 1580 1581 1582 1583
          perButtonConstraints,
          parentUsesSize: true,
        );

        // The 2nd button needs to be offset to the right.
1584
        assert(lastChild!.parentData is MultiChildLayoutParentData);
1585
        final MultiChildLayoutParentData secondButtonParentData = lastChild!.parentData! as MultiChildLayoutParentData;
1586
        secondButtonParentData.offset = Offset(firstChild!.size.width + dividerThickness, 0.0);
1587 1588 1589

        // Calculate our size based on the button sizes.
        size = constraints.constrain(
1590
          Size(
1591 1592
            dialogWidth,
            math.max(
1593 1594
              firstChild!.size.height,
              lastChild!.size.height,
1595
            ),
1596
          ),
1597 1598 1599 1600 1601 1602 1603 1604 1605
        );
      }
    } else {
      // We need to stack buttons vertically, plus dividers above each button (except the 1st).
      final BoxConstraints perButtonConstraints = constraints.copyWith(
        minHeight: 0.0,
        maxHeight: double.infinity,
      );

1606
      RenderBox? child = firstChild;
1607 1608 1609 1610 1611 1612 1613 1614 1615
      int index = 0;
      double verticalOffset = 0.0;
      while (child != null) {
        child.layout(
          perButtonConstraints,
          parentUsesSize: true,
        );

        assert(child.parentData is MultiChildLayoutParentData);
1616
        final MultiChildLayoutParentData parentData = child.parentData! as MultiChildLayoutParentData;
1617
        parentData.offset = Offset(0.0, verticalOffset);
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

        verticalOffset += child.size.height;
        if (index < childCount - 1) {
          // Add a gap for the next divider.
          verticalOffset += dividerThickness;
        }

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

      // Our height is the accumulated height of all buttons and dividers.
      size = constraints.constrain(
1631
        Size(dialogWidth, verticalOffset)
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
      );
    }
  }

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

    if (_isSingleButtonRow(size.width)) {
      _drawButtonBackgroundsAndDividersSingleRow(canvas, offset);
    } else {
      _drawButtonBackgroundsAndDividersStacked(canvas, offset);
    }

    _drawButtons(context, offset);
  }

  void _drawButtonBackgroundsAndDividersSingleRow(Canvas canvas, Offset offset) {
    // The vertical divider sits between the left button and right button (if
    // the dialog has 2 buttons).  The vertical divider is hidden if either the
    // left or right button is pressed.
    final Rect verticalDivider = childCount == 2 && !_isButtonPressed
1654
      ? Rect.fromLTWH(
1655
          offset.dx + firstChild!.size.width,
1656 1657 1658
          offset.dy,
          dividerThickness,
          math.max(
1659 1660
            firstChild!.size.height,
            lastChild!.size.height,
1661 1662 1663 1664
          ),
        )
      : Rect.zero;

1665
    final List<Rect> pressedButtonRects = _pressedButtons.map<Rect>((RenderBox pressedButton) {
1666
      final MultiChildLayoutParentData buttonParentData = pressedButton.parentData! as MultiChildLayoutParentData;
1667

1668
      return Rect.fromLTWH(
1669 1670 1671 1672 1673 1674 1675 1676
        offset.dx + buttonParentData.offset.dx,
        offset.dy + buttonParentData.offset.dy,
        pressedButton.size.width,
        pressedButton.size.height,
      );
    }).toList();

    // Create the button backgrounds path and paint it.
1677
    final Path backgroundFillPath = Path()
1678
      ..fillType = PathFillType.evenOdd
1679
      ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height))
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
      ..addRect(verticalDivider);

    for (int i = 0; i < pressedButtonRects.length; i += 1) {
      backgroundFillPath.addRect(pressedButtonRects[i]);
    }

    canvas.drawPath(
      backgroundFillPath,
      _buttonBackgroundPaint,
    );

    // Create the pressed buttons background path and paint it.
1692
    final Path pressedBackgroundFillPath = Path();
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    for (int i = 0; i < pressedButtonRects.length; i += 1) {
      pressedBackgroundFillPath.addRect(pressedButtonRects[i]);
    }

    canvas.drawPath(
      pressedBackgroundFillPath,
      _pressedButtonBackgroundPaint,
    );

    // Create the dividers path and paint it.
1703
    final Path dividersPath = Path()
1704 1705 1706 1707 1708 1709 1710 1711 1712
      ..addRect(verticalDivider);

    canvas.drawPath(
      dividersPath,
      _dividerPaint,
    );
  }

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

1715
    final Path backgroundFillPath = Path()
1716
      ..fillType = PathFillType.evenOdd
1717
      ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height));
1718

1719
    final Path pressedBackgroundFillPath = Path();
1720

1721
    final Path dividersPath = Path();
1722 1723 1724

    Offset accumulatingOffset = offset;

1725 1726
    RenderBox? child = firstChild;
    RenderBox? prevChild;
1727 1728
    while (child != null) {
      assert(child.parentData is _ActionButtonParentData);
1729
      final _ActionButtonParentData currentButtonParentData = child.parentData! as _ActionButtonParentData;
1730 1731 1732 1733 1734
      final bool isButtonPressed = currentButtonParentData.isPressed;

      bool isPrevButtonPressed = false;
      if (prevChild != null) {
        assert(prevChild.parentData is _ActionButtonParentData);
1735
        final _ActionButtonParentData previousButtonParentData = prevChild.parentData! as _ActionButtonParentData;
1736 1737 1738 1739 1740
        isPrevButtonPressed = previousButtonParentData.isPressed;
      }

      final bool isDividerPresent = child != firstChild;
      final bool isDividerPainted = isDividerPresent && !(isButtonPressed || isPrevButtonPressed);
1741
      final Rect dividerRect = Rect.fromLTWH(
1742 1743 1744 1745 1746 1747
        accumulatingOffset.dx,
        accumulatingOffset.dy,
        size.width,
        dividerThickness,
      );

1748
      final Rect buttonBackgroundRect = Rect.fromLTWH(
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
        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)
1771
          + Offset(0.0, child.size.height);
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

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

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

  void _drawButtons(PaintingContext context, Offset offset) {
1783
    RenderBox? child = firstChild;
1784
    while (child != null) {
1785
      final MultiChildLayoutParentData childParentData = child.parentData! as MultiChildLayoutParentData;
1786 1787 1788 1789 1790 1791
      context.paintChild(child, childParentData.offset + offset);
      child = childAfter(child);
    }
  }

  @override
1792
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
1793 1794
    return defaultHitTestChildren(result, position: position);
  }
1795
}