dialog.dart 36.5 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:ui';
6

xster's avatar
xster committed
7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/widgets.dart';
9

10
import 'button_bar.dart';
11
import 'colors.dart';
12
import 'debug.dart';
13
import 'dialog_theme.dart';
14
import 'ink_well.dart';
15
import 'material.dart';
16
import 'material_localizations.dart';
17
import 'theme.dart';
18
import 'theme_data.dart';
19

20 21
// Examples can assume:
// enum Department { treasury, state }
22
// BuildContext context;
23

24 25
const EdgeInsets _defaultInsetPadding = EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0);

26
/// A material design dialog.
27
///
28 29 30 31
/// This dialog widget does not have any opinion about the contents of the
/// dialog. Rather than using this widget directly, consider using [AlertDialog]
/// or [SimpleDialog], which implement specific kinds of material design
/// dialogs.
32 33
///
/// See also:
Ian Hickson's avatar
Ian Hickson committed
34
///
35 36 37
///  * [AlertDialog], for dialogs that have a message and some buttons.
///  * [SimpleDialog], for dialogs that offer a variety of options.
///  * [showDialog], which actually displays the dialog and returns its result.
38
///  * <https://material.io/design/components/dialogs.html>
39
class Dialog extends StatelessWidget {
40 41 42
  /// Creates a dialog.
  ///
  /// Typically used in conjunction with [showDialog].
43
  const Dialog({
44
    Key? key,
45 46
    this.backgroundColor,
    this.elevation,
47 48
    this.insetAnimationDuration = const Duration(milliseconds: 100),
    this.insetAnimationCurve = Curves.decelerate,
49 50
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
51
    this.shape,
52
    this.child,
53 54
  }) : assert(clipBehavior != null),
       super(key: key);
55

56 57
  /// {@template flutter.material.dialog.backgroundColor}
  /// The background color of the surface of this [Dialog].
58
  ///
59 60 61 62
  /// This sets the [Material.color] on this [Dialog]'s [Material].
  ///
  /// If `null`, [ThemeData.cardColor] is used.
  /// {@endtemplate}
63
  final Color? backgroundColor;
64 65 66 67 68 69 70 71

  /// {@template flutter.material.dialog.elevation}
  /// The z-coordinate of this [Dialog].
  ///
  /// If null then [DialogTheme.elevation] is used, and if that's null then the
  /// dialog's elevation is 24.0.
  /// {@endtemplate}
  /// {@macro flutter.material.material.elevation}
72
  final double? elevation;
73

74
  /// {@template flutter.material.dialog.insetAnimationDuration}
75 76 77 78
  /// The duration of the animation to show when the system keyboard intrudes
  /// into the space that the dialog is placed in.
  ///
  /// Defaults to 100 milliseconds.
79
  /// {@endtemplate}
80 81
  final Duration insetAnimationDuration;

82
  /// {@template flutter.material.dialog.insetAnimationCurve}
83 84 85
  /// The curve to use for the animation shown when the system keyboard intrudes
  /// into the space that the dialog is placed in.
  ///
86
  /// Defaults to [Curves.decelerate].
87
  /// {@endtemplate}
88 89
  final Curve insetAnimationCurve;

90 91 92 93 94 95 96
  /// {@template flutter.material.dialog.insetPadding}
  /// The amount of padding added to [MediaQueryData.viewInsets] on the outside
  /// of the dialog. This defines the minimum space between the screen's edges
  /// and the dialog.
  ///
  /// Defaults to `EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0)`.
  /// {@endtemplate}
97
  final EdgeInsets? insetPadding;
98 99 100 101 102 103 104 105 106 107 108 109

  /// {@template flutter.material.dialog.clipBehavior}
  /// Controls how the contents of the dialog are clipped (or not) to the given
  /// [shape].
  ///
  /// See the enum [Clip] for details of all possible options and their common
  /// use cases.
  ///
  /// Defaults to [Clip.none], and must not be null.
  /// {@endtemplate}
  final Clip clipBehavior;

110 111 112 113 114
  /// {@template flutter.material.dialog.shape}
  /// The shape of this dialog's border.
  ///
  /// Defines the dialog's [Material.shape].
  ///
115
  /// The default shape is a [RoundedRectangleBorder] with a radius of 4.0
116
  /// {@endtemplate}
117
  final ShapeBorder? shape;
118

119 120 121
  /// The widget below this widget in the tree.
  ///
  /// {@macro flutter.widgets.child}
122
  final Widget? child;
123

124
  static const RoundedRectangleBorder _defaultDialogShape =
125
    RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
126
  static const double _defaultElevation = 24.0;
127

128 129
  @override
  Widget build(BuildContext context) {
130
    final DialogTheme dialogTheme = DialogTheme.of(context);
131
    final EdgeInsets effectivePadding = MediaQuery.of(context).viewInsets + (insetPadding ?? const EdgeInsets.all(0.0));
132
    return AnimatedPadding(
133
      padding: effectivePadding,
134 135
      duration: insetAnimationDuration,
      curve: insetAnimationCurve,
136
      child: MediaQuery.removeViewInsets(
137 138 139 140 141
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
142 143
        child: Center(
          child: ConstrainedBox(
144
            constraints: const BoxConstraints(minWidth: 280.0),
145
            child: Material(
146
              color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context)!.dialogBackgroundColor,
147
              elevation: elevation ?? dialogTheme.elevation ?? _defaultElevation,
148
              shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
149
              type: MaterialType.card,
150
              clipBehavior: clipBehavior,
151 152 153 154 155
              child: child,
            ),
          ),
        ),
      ),
156 157 158 159 160 161 162 163 164 165 166
    );
  }
}

/// A material design alert dialog.
///
/// An alert dialog informs the user about situations that require
/// acknowledgement. An alert dialog has an optional title and an optional list
/// of actions. The title is displayed above the content and the actions are
/// displayed below the content.
///
167 168
/// {@youtube 560 315 https://www.youtube.com/watch?v=75CsnyRXf5I}
///
169 170 171 172 173 174 175 176 177
/// If the content is too large to fit on the screen vertically, the dialog will
/// display the title and the actions and let the content overflow, which is
/// rarely desired. Consider using a scrolling widget for [content], such as
/// [SingleChildScrollView], to avoid overflow. (However, be aware that since
/// [AlertDialog] tries to size itself using the intrinsic dimensions of its
/// children, widgets such as [ListView], [GridView], and [CustomScrollView],
/// which use lazy viewports, will not work. If this is a problem, consider
/// using [Dialog] directly.)
///
178 179 180 181 182 183
/// For dialogs that offer the user a choice between several options, consider
/// using a [SimpleDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
184 185
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/alert_dialog.mp4}
///
186
/// {@tool snippet}
187 188 189 190 191
///
/// This snippet shows a method in a [State] which, when called, displays a dialog box
/// and returns a [Future] that completes when the dialog is dismissed.
///
/// ```dart
192
/// Future<void> _showMyDialog() async {
193
///   return showDialog<void>(
194 195
///     context: context,
///     barrierDismissible: false, // user must tap button!
196
///     builder: (BuildContext context) {
197
///       return AlertDialog(
198
///         title: Text('AlertDialog Title'),
199 200 201
///         content: SingleChildScrollView(
///           child: ListBody(
///             children: <Widget>[
202 203
///               Text('This is a demo alert dialog.'),
///               Text('Would you like to approve of this message?'),
204 205
///             ],
///           ),
206
///         ),
207
///         actions: <Widget>[
208
///           TextButton(
209
///             child: Text('Approve'),
210 211 212 213 214 215 216
///             onPressed: () {
///               Navigator.of(context).pop();
///             },
///           ),
///         ],
///       );
///     },
217 218 219
///   );
/// }
/// ```
220
/// {@end-tool}
221
///
222 223
/// See also:
///
224 225
///  * [SimpleDialog], which handles the scrolling of the contents but has no [actions].
///  * [Dialog], on which [AlertDialog] and [SimpleDialog] are based.
226
///  * [CupertinoAlertDialog], an iOS-styled alert dialog.
227
///  * [showDialog], which actually displays the dialog and returns its result.
228
///  * <https://material.io/design/components/dialogs.html#alert-dialog>
229 230 231 232
class AlertDialog extends StatelessWidget {
  /// Creates an alert dialog.
  ///
  /// Typically used in conjunction with [showDialog].
233 234 235 236
  ///
  /// The [contentPadding] must not be null. The [titlePadding] defaults to
  /// null, which implies a default that depends on the values of the other
  /// properties. See the documentation of [titlePadding] for details.
237
  const AlertDialog({
238
    Key? key,
239
    this.title,
240
    this.titlePadding,
241
    this.titleTextStyle,
242
    this.content,
243
    this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
244
    this.contentTextStyle,
245
    this.actions,
246
    this.actionsPadding = EdgeInsets.zero,
247
    this.actionsOverflowDirection,
248
    this.actionsOverflowButtonSpacing,
249
    this.buttonPadding,
250 251
    this.backgroundColor,
    this.elevation,
252
    this.semanticLabel,
253 254
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
255
    this.shape,
256
    this.scrollable = false,
257
  }) : assert(contentPadding != null),
258
       assert(clipBehavior != null),
259
       super(key: key);
260 261 262

  /// The (optional) title of the dialog is displayed in a large font at the top
  /// of the dialog.
Ian Hickson's avatar
Ian Hickson committed
263 264
  ///
  /// Typically a [Text] widget.
265
  final Widget? title;
266

267 268
  /// Padding around the title.
  ///
269 270 271 272 273 274 275 276
  /// If there is no title, no padding will be provided. Otherwise, this padding
  /// is used.
  ///
  /// This property defaults to providing 24 pixels on the top, left, and right
  /// of the title. If the [content] is not null, then no bottom padding is
  /// provided (but see [contentPadding]). If it _is_ null, then an extra 20
  /// pixels of bottom padding is added to separate the [title] from the
  /// [actions].
277
  final EdgeInsetsGeometry? titlePadding;
278

279 280
  /// Style for the text in the [title] of this [AlertDialog].
  ///
281 282
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
  /// [TextTheme.headline6] of [ThemeData.textTheme].
283
  final TextStyle? titleTextStyle;
284

285 286
  /// The (optional) content of the dialog is displayed in the center of the
  /// dialog in a lighter font.
Ian Hickson's avatar
Ian Hickson committed
287
  ///
288 289 290 291
  /// Typically this is a [SingleChildScrollView] that contains the dialog's
  /// message. As noted in the [AlertDialog] documentation, it's important
  /// to use a [SingleChildScrollView] if there's any risk that the content
  /// will not fit.
292
  final Widget? content;
293

294 295
  /// Padding around the content.
  ///
296 297 298 299
  /// If there is no content, no padding will be provided. Otherwise, padding of
  /// 20 pixels is provided above the content to separate the content from the
  /// title, and padding of 24 pixels is provided on the left, right, and bottom
  /// to separate the content from the other edges of the dialog.
300
  final EdgeInsetsGeometry contentPadding;
301

302 303
  /// Style for the text in the [content] of this [AlertDialog].
  ///
304 305
  /// If null, [DialogTheme.contentTextStyle] is used. If that's null, defaults
  /// to [TextTheme.subtitle1] of [ThemeData.textTheme].
306
  final TextStyle? contentTextStyle;
307

308 309
  /// The (optional) set of actions that are displayed at the bottom of the
  /// dialog.
Ian Hickson's avatar
Ian Hickson committed
310
  ///
311
  /// Typically this is a list of [TextButton] widgets. It is recommended to
312
  /// set the [Text.textAlign] to [TextAlign.end] for the [Text] within the
313
  /// [TextButton], so that buttons whose labels wrap to an extra line align
314
  /// with the overall [ButtonBar]'s alignment within the dialog.
Ian Hickson's avatar
Ian Hickson committed
315
  ///
316 317 318 319 320 321
  /// These widgets will be wrapped in a [ButtonBar], which introduces 8 pixels
  /// of padding on each side.
  ///
  /// If the [title] is not null but the [content] _is_ null, then an extra 20
  /// pixels of padding is added above the [ButtonBar] to separate the [title]
  /// from the [actions].
322
  final List<Widget>? actions;
323

Dan Field's avatar
Dan Field committed
324
  /// Padding around the set of [actions] at the bottom of the dialog.
325 326 327 328 329 330 331 332 333
  ///
  /// Typically used to provide padding to the button bar between the button bar
  /// and the edges of the dialog.
  ///
  /// If are no [actions], then no padding will be included. The padding around
  /// the button bar defaults to zero. It is also important to note that
  /// [buttonPadding] may contribute to the padding on the edges of [actions] as
  /// well.
  ///
334
  /// {@tool snippet}
335 336 337 338 339 340
  /// This is an example of a set of actions aligned with the content widget.
  /// ```dart
  /// AlertDialog(
  ///   title: Text('Title'),
  ///   content: Container(width: 200, height: 200, color: Colors.green),
  ///   actions: <Widget>[
341 342
  ///     ElevatedButton(onPressed: () {}, child: Text('Button 1')),
  ///     ElevatedButton(onPressed: () {}, child: Text('Button 2')),
343 344 345 346 347
  ///   ],
  ///   actionsPadding: EdgeInsets.symmetric(horizontal: 8.0),
  /// )
  /// ```
  /// {@end-tool}
348 349 350 351
  ///
  /// See also:
  ///
  /// * [ButtonBar], which [actions] configures to lay itself out.
352 353
  final EdgeInsetsGeometry actionsPadding;

354 355 356 357 358 359 360 361 362 363 364 365
  /// The vertical direction of [actions] if the children overflow
  /// horizontally.
  ///
  /// If the dialog's [actions] do not fit into a single row, then they
  /// are arranged in a column. The first action is at the top of the
  /// column if this property is set to [VerticalDirection.down], since it
  /// "starts" at the top and "ends" at the bottom. On the other hand,
  /// the first action will be at the bottom of the column if this
  /// property is set to [VerticalDirection.up], since it "starts" at the
  /// bottom and "ends" at the top.
  ///
  /// If null then it will use the surrounding
366
  /// [ButtonBarThemeData.overflowDirection]. If that is null, it will
367 368 369 370 371
  /// default to [VerticalDirection.down].
  ///
  /// See also:
  ///
  /// * [ButtonBar], which [actions] configures to lay itself out.
372
  final VerticalDirection? actionsOverflowDirection;
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387
  /// The spacing between [actions] when the button bar overflows.
  ///
  /// If the widgets in [actions] do not fit into a single row, they are
  /// arranged into a column. This parameter provides additional
  /// vertical space in between buttons when it does overflow.
  ///
  /// Note that the button spacing may appear to be more than
  /// the value provided. This is because most buttons adhere to the
  /// [MaterialTapTargetSize] of 48px. So, even though a button
  /// might visually be 36px in height, it might still take up to
  /// 48px vertically.
  ///
  /// If null then no spacing will be added in between buttons in
  /// an overflow state.
388
  final double? actionsOverflowButtonSpacing;
389

390 391 392 393 394 395
  /// The padding that surrounds each button in [actions].
  ///
  /// This is different from [actionsPadding], which defines the padding
  /// between the entire button bar and the edges of the dialog.
  ///
  /// If this property is null, then it will use the surrounding
396
  /// [ButtonBarThemeData.buttonPadding]. If that is null, it will default to
397
  /// 8.0 logical pixels on the left and right.
398 399 400 401
  ///
  /// See also:
  ///
  /// * [ButtonBar], which [actions] configures to lay itself out.
402
  final EdgeInsetsGeometry? buttonPadding;
403

404
  /// {@macro flutter.material.dialog.backgroundColor}
405
  final Color? backgroundColor;
406 407 408

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
409
  final double? elevation;
410

411
  /// The semantic label of the dialog used by accessibility frameworks to
412
  /// announce screen transitions when the dialog is opened and closed.
413
  ///
414 415 416 417 418
  /// In iOS, if this label is not provided, a semantic label will be inferred
  /// from the [title] if it is not null.
  ///
  /// In Android, if this label is not provided, the dialog will use the
  /// [MaterialLocalizations.alertDialogLabel] as its label.
419
  ///
420
  /// See also:
421
  ///
422
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
423
  ///    value is used.
424
  final String? semanticLabel;
425

426 427 428 429 430 431
  /// {@macro flutter.material.dialog.insetPadding}
  final EdgeInsets insetPadding;

  /// {@macro flutter.material.dialog.clipBehavior}
  final Clip clipBehavior;

432
  /// {@macro flutter.material.dialog.shape}
433
  final ShapeBorder? shape;
434

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  /// Determines whether the [title] and [content] widgets are wrapped in a
  /// scrollable.
  ///
  /// This configuration is used when the [title] and [content] are expected
  /// to overflow. Both [title] and [content] are wrapped in a scroll view,
  /// allowing all overflowed content to be visible while still showing the
  /// button bar.
  @Deprecated(
    'Set scrollable to `true`. This parameter will be removed and '
    'was introduced to migrate AlertDialog to be scrollable by '
    'default. For more information, see '
    'https://flutter.dev/docs/release/breaking-changes/scrollable_alert_dialog. '
    'This feature was deprecated after v1.13.2.'
  )
  final bool scrollable;

451
  @override
452
  Widget build(BuildContext context) {
453
    assert(debugCheckHasMaterialLocalizations(context));
454
    final ThemeData theme = Theme.of(context)!;
455
    final DialogTheme dialogTheme = DialogTheme.of(context);
456

457
    String? label = semanticLabel;
458 459 460 461 462 463 464 465
    switch (theme.platform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
466
        label ??= MaterialLocalizations.of(context).alertDialogLabel;
467 468
    }

469 470
    // The paddingScaleFactor is used to adjust the padding of Dialog's
    // children.
471
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
472
    final TextDirection? textDirection = Directionality.maybeOf(context);
473

474 475 476
    Widget? titleWidget;
    Widget? contentWidget;
    Widget? actionsWidget;
477 478 479 480 481 482 483 484 485 486
    if (title != null) {
      final EdgeInsets defaultTitlePadding = EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0);
      final EdgeInsets effectiveTitlePadding = titlePadding?.resolve(textDirection) ?? defaultTitlePadding;
      titleWidget = Padding(
        padding: EdgeInsets.only(
          left: effectiveTitlePadding.left * paddingScaleFactor,
          right: effectiveTitlePadding.right * paddingScaleFactor,
          top: effectiveTitlePadding.top * paddingScaleFactor,
          bottom: effectiveTitlePadding.bottom,
        ),
487
        child: DefaultTextStyle(
488
          style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.headline6!,
489 490
          child: Semantics(
            child: title,
491
            namesRoute: label == null,
492 493 494 495
            container: true,
          ),
        ),
      );
496
    }
497

498 499
    if (content != null) {
      final EdgeInsets effectiveContentPadding = contentPadding.resolve(textDirection);
500
      contentWidget = Padding(
501 502 503 504 505 506
        padding: EdgeInsets.only(
          left: effectiveContentPadding.left * paddingScaleFactor,
          right: effectiveContentPadding.right * paddingScaleFactor,
          top: title == null ? effectiveContentPadding.top * paddingScaleFactor : effectiveContentPadding.top,
          bottom: effectiveContentPadding.bottom,
        ),
507
        child: DefaultTextStyle(
508 509
          style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subtitle1!,
          child: content!,
510 511
        ),
      );
512 513
    }

514

515
    if (actions != null) {
516 517 518 519
      actionsWidget = Padding(
        padding: actionsPadding,
        child: ButtonBar(
          buttonPadding: buttonPadding,
520
          overflowDirection: actionsOverflowDirection,
521
          overflowButtonSpacing: actionsOverflowButtonSpacing,
522
          children: actions!,
523 524
        ),
      );
525
    }
526

527 528 529 530 531 532 533 534 535 536
    List<Widget> columnChildren;
    if (scrollable) {
      columnChildren = <Widget>[
        if (title != null || content != null)
          Flexible(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
537 538
                  if (title != null) titleWidget!,
                  if (content != null) contentWidget!,
539 540 541 542 543
                ],
              ),
            ),
          ),
        if (actions != null)
544
          actionsWidget!,
545 546 547
      ];
    } else {
      columnChildren = <Widget>[
548 549 550
        if (title != null) titleWidget!,
        if (content != null) Flexible(child: contentWidget!),
        if (actions != null) actionsWidget!,
551 552 553
      ];
    }

554 555
    Widget dialogChild = IntrinsicWidth(
      child: Column(
556 557
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
558
        children: columnChildren,
559
      ),
560
    );
561 562

    if (label != null)
563
      dialogChild = Semantics(
564 565
        scopesRoute: true,
        explicitChildNodes: true,
566 567
        namesRoute: true,
        label: label,
568
        child: dialogChild,
569 570
      );

571 572 573
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
574 575
      insetPadding: insetPadding,
      clipBehavior: clipBehavior,
576 577 578
      shape: shape,
      child: dialogChild,
    );
579 580 581
  }
}

582 583 584 585 586 587 588
/// An option used in a [SimpleDialog].
///
/// A simple dialog offers the user a choice between several options. This
/// widget is commonly used to represent each of the options. If the user
/// selects this option, the widget will call the [onPressed] callback, which
/// typically uses [Navigator.pop] to close the dialog.
///
589 590 591 592 593 594
/// The padding on a [SimpleDialogOption] is configured to combine with the
/// default [SimpleDialog.contentPadding] so that each option ends up 8 pixels
/// from the other vertically, with 20 pixels of spacing between the dialog's
/// title and the first option, and 24 pixels of spacing between the last option
/// and the bottom of the dialog.
///
595
/// {@tool snippet}
596 597
///
/// ```dart
598
/// SimpleDialogOption(
599 600 601 602
///   onPressed: () { Navigator.pop(context, Department.treasury); },
///   child: const Text('Treasury department'),
/// )
/// ```
603
/// {@end-tool}
604
///
605 606 607 608
/// See also:
///
///  * [SimpleDialog], for a dialog in which to use this widget.
///  * [showDialog], which actually displays the dialog and returns its result.
609
///  * [TextButton], which are commonly used as actions in other kinds of
610
///    dialogs, such as [AlertDialog]s.
611
///  * <https://material.io/design/components/dialogs.html#simple-dialog>
612 613
class SimpleDialogOption extends StatelessWidget {
  /// Creates an option for a [SimpleDialog].
614
  const SimpleDialogOption({
615
    Key? key,
616
    this.onPressed,
617
    this.padding,
618 619 620 621 622 623
    this.child,
  }) : super(key: key);

  /// The callback that is called when this option is selected.
  ///
  /// If this is set to null, the option cannot be selected.
624 625 626
  ///
  /// When used in a [SimpleDialog], this will typically call [Navigator.pop]
  /// with a value for [showDialog] to complete its future with.
627
  final VoidCallback? onPressed;
628 629 630 631

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

634 635 636
  /// The amount of space to surround the [child] with.
  ///
  /// Defaults to EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0).
637
  final EdgeInsets? padding;
638

639 640
  @override
  Widget build(BuildContext context) {
641
    return InkWell(
642
      onTap: onPressed,
643
      child: Padding(
644
        padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
645
        child: child,
646 647 648 649 650
      ),
    );
  }
}

651 652 653 654 655
/// A simple material design dialog.
///
/// A simple dialog offers the user a choice between several options. A simple
/// dialog has an optional title that is displayed above the choices.
///
656 657 658 659
/// Choices are normally represented using [SimpleDialogOption] widgets. If
/// other widgets are used, see [contentPadding] for notes regarding the
/// conventions for obtaining the spacing expected by Material Design.
///
660 661 662 663 664 665
/// For dialogs that inform the user about a situation, consider using an
/// [AlertDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
666 667
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/simple_dialog.mp4}
///
668
/// {@tool snippet}
669 670 671 672 673 674 675 676 677 678 679 680 681
///
/// In this example, the user is asked to select between two options. These
/// options are represented as an enum. The [showDialog] method here returns
/// a [Future] that completes to a value of that enum. If the user cancels
/// the dialog (e.g. by hitting the back button on Android, or tapping on the
/// mask behind the dialog) then the future completes with the null value.
///
/// The return value in this example is used as the index for a switch statement.
/// One advantage of using an enum as the return value and then using that to
/// drive a switch statement is that the analyzer will flag any switch statement
/// that doesn't mention every value in the enum.
///
/// ```dart
682
/// Future<void> _askedToLead() async {
683 684
///   switch (await showDialog<Department>(
///     context: context,
685
///     builder: (BuildContext context) {
686
///       return SimpleDialog(
687 688
///         title: const Text('Select assignment'),
///         children: <Widget>[
689
///           SimpleDialogOption(
690 691 692
///             onPressed: () { Navigator.pop(context, Department.treasury); },
///             child: const Text('Treasury department'),
///           ),
693
///           SimpleDialogOption(
694 695 696 697 698 699
///             onPressed: () { Navigator.pop(context, Department.state); },
///             child: const Text('State department'),
///           ),
///         ],
///       );
///     }
700 701 702 703 704 705 706 707 708 709 710
///   )) {
///     case Department.treasury:
///       // Let's go.
///       // ...
///     break;
///     case Department.state:
///       // ...
///     break;
///   }
/// }
/// ```
711
/// {@end-tool}
712
///
713 714
/// See also:
///
715
///  * [SimpleDialogOption], which are options used in this type of dialog.
716 717 718
///  * [AlertDialog], for dialogs that have a row of buttons below the body.
///  * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
///  * [showDialog], which actually displays the dialog and returns its result.
719
///  * <https://material.io/design/components/dialogs.html#simple-dialog>
720 721 722 723
class SimpleDialog extends StatelessWidget {
  /// Creates a simple dialog.
  ///
  /// Typically used in conjunction with [showDialog].
724 725
  ///
  /// The [titlePadding] and [contentPadding] arguments must not be null.
726
  const SimpleDialog({
727
    Key? key,
728
    this.title,
729
    this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
730
    this.titleTextStyle,
731
    this.children,
732
    this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
733 734
    this.backgroundColor,
    this.elevation,
735
    this.semanticLabel,
736
    this.shape,
737 738 739
  }) : assert(titlePadding != null),
       assert(contentPadding != null),
       super(key: key);
740 741 742 743 744

  /// The (optional) title of the dialog is displayed in a large font at the top
  /// of the dialog.
  ///
  /// Typically a [Text] widget.
745
  final Widget? title;
746 747 748

  /// Padding around the title.
  ///
749 750 751 752 753 754 755
  /// If there is no title, no padding will be provided.
  ///
  /// By default, this provides the recommend Material Design padding of 24
  /// pixels around the left, top, and right edges of the title.
  ///
  /// See [contentPadding] for the conventions regarding padding between the
  /// [title] and the [children].
756
  final EdgeInsetsGeometry titlePadding;
757

758 759
  /// Style for the text in the [title] of this [SimpleDialog].
  ///
760
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
761
  /// [TextTheme.headline6] of [ThemeData.textTheme].
762
  final TextStyle? titleTextStyle;
763

764 765
  /// The (optional) content of the dialog is displayed in a
  /// [SingleChildScrollView] underneath the title.
766
  ///
767
  /// Typically a list of [SimpleDialogOption]s.
768
  final List<Widget>? children;
769 770 771

  /// Padding around the content.
  ///
772 773 774 775 776 777 778 779 780 781
  /// By default, this is 12 pixels on the top and 16 pixels on the bottom. This
  /// is intended to be combined with children that have 24 pixels of padding on
  /// the left and right, and 8 pixels of padding on the top and bottom, so that
  /// the content ends up being indented 20 pixels from the title, 24 pixels
  /// from the bottom, and 24 pixels from the sides.
  ///
  /// The [SimpleDialogOption] widget uses such padding.
  ///
  /// If there is no [title], the [contentPadding] should be adjusted so that
  /// the top padding ends up being 24 pixels.
782
  final EdgeInsetsGeometry contentPadding;
783

784
  /// {@macro flutter.material.dialog.backgroundColor}
785
  final Color? backgroundColor;
786 787 788

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
789
  final double? elevation;
790

791
  /// The semantic label of the dialog used by accessibility frameworks to
792
  /// announce screen transitions when the dialog is opened and closed.
793
  ///
794
  /// If this label is not provided, a semantic label will be inferred from the
795 796
  /// [title] if it is not null.  If there is no title, the label will be taken
  /// from [MaterialLocalizations.dialogLabel].
797
  ///
798
  /// See also:
799
  ///
800
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
801
  ///    value is used.
802
  final String? semanticLabel;
803

804
  /// {@macro flutter.material.dialog.shape}
805
  final ShapeBorder? shape;
806

807 808
  @override
  Widget build(BuildContext context) {
809
    assert(debugCheckHasMaterialLocalizations(context));
810
    final ThemeData theme = Theme.of(context)!;
811

812
    String? label = semanticLabel;
813
    if (title == null) {
814
      switch (theme.platform) {
815
        case TargetPlatform.macOS:
816 817 818 819
        case TargetPlatform.iOS:
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
820 821
        case TargetPlatform.linux:
        case TargetPlatform.windows:
822
          label = semanticLabel ?? MaterialLocalizations.of(context).dialogLabel;
823
      }
824 825
    }

826 827
    // The paddingScaleFactor is used to adjust the padding of Dialog
    // children.
828
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
829
    final TextDirection? textDirection = Directionality.maybeOf(context);
830

831
    Widget? titleWidget;
832 833 834 835 836 837 838 839 840 841
    if (title != null) {
      final EdgeInsets effectiveTitlePadding = titlePadding.resolve(textDirection);
      titleWidget = Padding(
        padding: EdgeInsets.only(
          left: effectiveTitlePadding.left * paddingScaleFactor,
          right: effectiveTitlePadding.right * paddingScaleFactor,
          top: effectiveTitlePadding.top * paddingScaleFactor,
          bottom: children == null ? effectiveTitlePadding.bottom * paddingScaleFactor : effectiveTitlePadding.bottom,
        ),
        child: DefaultTextStyle(
842
          style: titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.headline6!,
843
          child: Semantics(namesRoute: label == null, child: title),
844 845 846 847
        ),
      );
    }

848
    Widget? contentWidget;
849 850 851 852 853 854 855 856 857 858
    if (children != null) {
      final EdgeInsets effectiveContentPadding = contentPadding.resolve(textDirection);
      contentWidget = Flexible(
        child: SingleChildScrollView(
          padding: EdgeInsets.only(
            left: effectiveContentPadding.left * paddingScaleFactor,
            right: effectiveContentPadding.right * paddingScaleFactor,
            top: title == null ? effectiveContentPadding.top * paddingScaleFactor : effectiveContentPadding.top,
            bottom: effectiveContentPadding.bottom * paddingScaleFactor,
          ),
859
          child: ListBody(children: children!),
860 861 862 863
        ),
      );
    }

864
    Widget dialogChild = IntrinsicWidth(
865
      stepWidth: 56.0,
866
      child: ConstrainedBox(
867
        constraints: const BoxConstraints(minWidth: 280.0),
868
        child: Column(
869 870
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
871
          children: <Widget>[
872 873
            if (title != null) titleWidget!,
            if (children != null) contentWidget!,
874
          ],
875 876
        ),
      ),
877
    );
878 879

    if (label != null)
880
      dialogChild = Semantics(
881 882
        scopesRoute: true,
        explicitChildNodes: true,
883 884 885 886
        namesRoute: true,
        label: label,
        child: dialogChild,
      );
887 888 889 890 891 892
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
      shape: shape,
      child: dialogChild,
    );
893 894
  }
}
895

896
Widget _buildMaterialDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
897 898
  return FadeTransition(
    opacity: CurvedAnimation(
899 900 901 902 903
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: child,
  );
904 905
}

906 907 908
/// Displays a Material dialog above the current contents of the app, with
/// Material entrance and exit animations, modal barrier color, and modal
/// barrier behavior (dialog is dismissible with a tap on the barrier).
909
///
910
/// This function takes a `builder` which typically builds a [Dialog] widget.
911 912 913 914
/// Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
/// `showDialog` is originally called from. Use a [StatefulBuilder] or a
/// custom [StatefulWidget] if the dialog needs to update dynamically.
915
///
916 917
/// The `child` argument is deprecated, and should be replaced with `builder`.
///
Ian Hickson's avatar
Ian Hickson committed
918 919 920 921
/// The `context` argument is used to look up the [Navigator] and [Theme] for
/// the dialog. It is only used when the method is called. Its corresponding
/// widget can be safely removed from the tree before the dialog is closed.
///
922 923 924 925
/// The `barrierDismissible` argument is used to indicate whether tapping on the
/// barrier will dismiss the dialog. It is `true` by default and can not be `null`.
///
/// The `barrierColor` argument is used to specify the color of the modal
926
/// barrier that darkens everything below the dialog. If `null` the default color
927 928 929 930
/// `Colors.black54` is used.
///
/// The `useSafeArea` argument is used to indicate if the dialog should only
/// display in 'safe' areas of the screen not used by the operating system
931
/// (see [SafeArea] for more details). It is `true` by default, which means
932
/// the dialog will not overlap operating system areas. If it is set to `false`
933 934
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
935 936 937
/// The `useRootNavigator` argument is used to determine whether to push the
/// dialog to the [Navigator] furthest from or nearest to the given `context`.
/// By default, `useRootNavigator` is `true` and the dialog route created by
938
/// this method is pushed to the root navigator. It can not be `null`.
939
///
940 941 942
/// The `routeSettings` argument is passed to [showGeneralDialog],
/// see [RouteSettings] for details.
///
943 944
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
945
/// dialog rather than just `Navigator.pop(context, result)`.
946
///
947 948 949
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
950
/// See also:
951
///
952 953 954
///  * [AlertDialog], for dialogs that have a row of buttons below a body.
///  * [SimpleDialog], which handles the scrolling of the contents and does
///    not show buttons below its body.
955
///  * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
956 957
///  * [showCupertinoDialog], which displays an iOS-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
958
///  * <https://material.io/design/components/dialogs.html>
959
Future<T?> showDialog<T>({
960 961
  required BuildContext context,
  WidgetBuilder? builder,
962
  bool barrierDismissible = true,
963
  Color? barrierColor,
964 965
  bool useSafeArea = true,
  bool useRootNavigator = true,
966
  RouteSettings? routeSettings,
967 968 969
  @Deprecated(
    'Instead of using the "child" argument, return the child from a closure '
    'provided to the "builder" argument. This will ensure that the BuildContext '
970 971 972
    'is appropriate for widgets built in the dialog. '
    'This feature was deprecated after v0.2.3.'
  )
973
  Widget? child,
974
}) {
975
  assert(child == null || builder == null);
976 977
  assert(barrierDismissible != null);
  assert(useSafeArea != null);
978
  assert(useRootNavigator != null);
979
  assert(debugCheckHasMaterialLocalizations(context));
980

981
  final CapturedThemes themes = InheritedTheme.capture(from: context, to: Navigator.of(context, rootNavigator: useRootNavigator)!.context);
982 983 984
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
985
      final Widget pageChild = child ?? Builder(builder: builder!);
986
      Widget dialog = themes.wrap(pageChild);
987 988 989 990
      if (useSafeArea) {
        dialog = SafeArea(child: dialog);
      }
      return dialog;
991
    },
992
    barrierDismissible: barrierDismissible,
993
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
994
    barrierColor: barrierColor ?? Colors.black54,
995 996
    transitionDuration: const Duration(milliseconds: 150),
    transitionBuilder: _buildMaterialDialogTransitions,
997
    useRootNavigator: useRootNavigator,
998
    routeSettings: routeSettings,
999
  );
1000
}
1001 1002 1003 1004 1005

double _paddingScaleFactor(double textScaleFactor) {
  final double clampedTextScaleFactor = textScaleFactor.clamp(1.0, 2.0).toDouble();
  // The final padding scale factor is clamped between 1/3 and 1. For example,
  // a non-scaled padding of 24 will produce a padding between 24 and 8.
1006
  return lerpDouble(1.0, 1.0 / 3.0, clampedTextScaleFactor - 1.0)!;
1007
}