dialog.dart 41.9 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

7
import 'package:flutter/widgets.dart';
8

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

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

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

25
/// A material design dialog.
26
///
27 28 29 30
/// 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.
31 32
///
/// See also:
Ian Hickson's avatar
Ian Hickson committed
33
///
34 35 36
///  * [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.
37
///  * <https://material.io/design/components/dialogs.html>
38
class Dialog extends StatelessWidget {
39 40 41
  /// Creates a dialog.
  ///
  /// Typically used in conjunction with [showDialog].
42
  const Dialog({
43
    Key? key,
44 45
    this.backgroundColor,
    this.elevation,
46 47
    this.insetAnimationDuration = const Duration(milliseconds: 100),
    this.insetAnimationCurve = Curves.decelerate,
48 49
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
50
    this.shape,
51
    this.child,
52 53
  }) : assert(clipBehavior != null),
       super(key: key);
54

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

  /// {@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}
71
  final double? elevation;
72

73
  /// {@template flutter.material.dialog.insetAnimationDuration}
74 75 76 77
  /// 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.
78
  /// {@endtemplate}
79 80
  final Duration insetAnimationDuration;

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

89 90 91 92 93 94 95
  /// {@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}
96
  final EdgeInsets? insetPadding;
97 98 99 100 101 102 103 104 105 106 107 108

  /// {@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;

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

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

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

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

/// 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.
///
166 167
/// {@youtube 560 315 https://www.youtube.com/watch?v=75CsnyRXf5I}
///
168 169 170 171 172 173 174 175 176
/// 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.)
///
177 178 179 180 181 182
/// 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.
///
183 184
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/alert_dialog.mp4}
///
185
/// {@tool snippet}
186 187 188 189 190
///
/// 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
191
/// Future<void> _showMyDialog() async {
192
///   return showDialog<void>(
193 194
///     context: context,
///     barrierDismissible: false, // user must tap button!
195
///     builder: (BuildContext context) {
196
///       return AlertDialog(
197
///         title: const Text('AlertDialog Title'),
198 199
///         content: SingleChildScrollView(
///           child: ListBody(
200
///             children: const <Widget>[
201 202
///               Text('This is a demo alert dialog.'),
///               Text('Would you like to approve of this message?'),
203 204
///             ],
///           ),
205
///         ),
206
///         actions: <Widget>[
207
///           TextButton(
208
///             child: const Text('Approve'),
209 210 211 212 213 214 215
///             onPressed: () {
///               Navigator.of(context).pop();
///             },
///           ),
///         ],
///       );
///     },
216 217 218
///   );
/// }
/// ```
219
/// {@end-tool}
220
///
221 222 223 224 225 226 227 228 229 230 231 232 233 234
/// {@tool dartpad --template=stateless_widget_scaffold_center}
///
/// This demo shows a [TextButton] which when pressed, calls [showDialog]. When called, this method
/// displays a Material dialog above the current contents of the app and returns
/// a [Future] that completes when the dialog is dismissed.
///
/// ```dart
/// Widget build(BuildContext context) {
///   return TextButton(
///     onPressed: () => showDialog<String>(
///       context: context,
///       builder: (BuildContext context) => AlertDialog(
///         title: const Text('AlertDialog Tilte'),
///         content: const Text('AlertDialog description'),
235
///         actions: <Widget>[
236 237 238 239 240 241 242 243 244 245 246
///           TextButton(
///             onPressed: () => Navigator.pop(context, 'Cancel'),
///             child: const Text('Cancel'),
///           ),
///           TextButton(
///             onPressed: () => Navigator.pop(context, 'OK'),
///             child: const Text('OK'),
///           ),
///         ],
///       ),
///     ),
247
///     child: const Text('Show Dialog'),
248 249 250 251 252 253
///   );
/// }
///
/// ```
/// {@end-tool}
///
254 255
/// See also:
///
256 257
///  * [SimpleDialog], which handles the scrolling of the contents but has no [actions].
///  * [Dialog], on which [AlertDialog] and [SimpleDialog] are based.
258
///  * [CupertinoAlertDialog], an iOS-styled alert dialog.
259
///  * [showDialog], which actually displays the dialog and returns its result.
260
///  * <https://material.io/design/components/dialogs.html#alert-dialog>
261 262 263 264
class AlertDialog extends StatelessWidget {
  /// Creates an alert dialog.
  ///
  /// Typically used in conjunction with [showDialog].
265 266 267 268
  ///
  /// 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.
269
  const AlertDialog({
270
    Key? key,
271
    this.title,
272
    this.titlePadding,
273
    this.titleTextStyle,
274
    this.content,
275
    this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
276
    this.contentTextStyle,
277
    this.actions,
278
    this.actionsPadding = EdgeInsets.zero,
279
    this.actionsOverflowDirection,
280
    this.actionsOverflowButtonSpacing,
281
    this.buttonPadding,
282 283
    this.backgroundColor,
    this.elevation,
284
    this.semanticLabel,
285 286
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
287
    this.shape,
288
    this.scrollable = false,
289
  }) : assert(contentPadding != null),
290
       assert(clipBehavior != null),
291
       super(key: key);
292 293 294

  /// 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
295 296
  ///
  /// Typically a [Text] widget.
297
  final Widget? title;
298

299 300
  /// Padding around the title.
  ///
301 302 303 304 305 306 307 308
  /// 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].
309
  final EdgeInsetsGeometry? titlePadding;
310

311 312
  /// Style for the text in the [title] of this [AlertDialog].
  ///
313 314
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
  /// [TextTheme.headline6] of [ThemeData.textTheme].
315
  final TextStyle? titleTextStyle;
316

317 318
  /// 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
319
  ///
320 321 322 323
  /// 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.
324
  final Widget? content;
325

326 327
  /// Padding around the content.
  ///
328 329 330 331
  /// 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.
332
  final EdgeInsetsGeometry contentPadding;
333

334 335
  /// Style for the text in the [content] of this [AlertDialog].
  ///
336 337
  /// If null, [DialogTheme.contentTextStyle] is used. If that's null, defaults
  /// to [TextTheme.subtitle1] of [ThemeData.textTheme].
338
  final TextStyle? contentTextStyle;
339

340 341
  /// The (optional) set of actions that are displayed at the bottom of the
  /// dialog.
Ian Hickson's avatar
Ian Hickson committed
342
  ///
343
  /// Typically this is a list of [TextButton] widgets. It is recommended to
344
  /// set the [Text.textAlign] to [TextAlign.end] for the [Text] within the
345
  /// [TextButton], so that buttons whose labels wrap to an extra line align
346
  /// with the overall [ButtonBar]'s alignment within the dialog.
Ian Hickson's avatar
Ian Hickson committed
347
  ///
348 349 350 351 352 353
  /// 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].
354
  final List<Widget>? actions;
355

Dan Field's avatar
Dan Field committed
356
  /// Padding around the set of [actions] at the bottom of the dialog.
357 358 359 360 361 362 363 364 365
  ///
  /// 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.
  ///
366
  /// {@tool snippet}
367 368 369
  /// This is an example of a set of actions aligned with the content widget.
  /// ```dart
  /// AlertDialog(
370
  ///   title: const Text('Title'),
371 372
  ///   content: Container(width: 200, height: 200, color: Colors.green),
  ///   actions: <Widget>[
373 374
  ///     ElevatedButton(onPressed: () {}, child: const Text('Button 1')),
  ///     ElevatedButton(onPressed: () {}, child: const Text('Button 2')),
375
  ///   ],
376
  ///   actionsPadding: const EdgeInsets.symmetric(horizontal: 8.0),
377 378 379
  /// )
  /// ```
  /// {@end-tool}
380 381 382 383
  ///
  /// See also:
  ///
  /// * [ButtonBar], which [actions] configures to lay itself out.
384 385
  final EdgeInsetsGeometry actionsPadding;

386 387 388 389 390 391 392 393 394 395 396 397
  /// 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
398
  /// [ButtonBarThemeData.overflowDirection]. If that is null, it will
399 400 401 402 403
  /// default to [VerticalDirection.down].
  ///
  /// See also:
  ///
  /// * [ButtonBar], which [actions] configures to lay itself out.
404
  final VerticalDirection? actionsOverflowDirection;
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419
  /// 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.
420
  final double? actionsOverflowButtonSpacing;
421

422 423 424 425 426
  /// 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.
  ///
427
  /// If this property is null, then it will default to
428
  /// 8.0 logical pixels on the left and right.
429
  final EdgeInsetsGeometry? buttonPadding;
430

431
  /// {@macro flutter.material.dialog.backgroundColor}
432
  final Color? backgroundColor;
433 434 435

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
436
  final double? elevation;
437

438
  /// The semantic label of the dialog used by accessibility frameworks to
439
  /// announce screen transitions when the dialog is opened and closed.
440
  ///
441 442 443 444 445
  /// 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.
446
  ///
447
  /// See also:
448
  ///
449
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
450
  ///    value is used.
451
  final String? semanticLabel;
452

453 454 455 456 457 458
  /// {@macro flutter.material.dialog.insetPadding}
  final EdgeInsets insetPadding;

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

459
  /// {@macro flutter.material.dialog.shape}
460
  final ShapeBorder? shape;
461

462 463 464 465 466 467 468 469 470
  /// 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.
  final bool scrollable;

471
  @override
472
  Widget build(BuildContext context) {
473
    assert(debugCheckHasMaterialLocalizations(context));
474
    final ThemeData theme = Theme.of(context);
475
    final DialogTheme dialogTheme = DialogTheme.of(context);
476

477
    String? label = semanticLabel;
478 479 480 481 482 483 484 485
    switch (theme.platform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
486
        label ??= MaterialLocalizations.of(context).alertDialogLabel;
487 488
    }

489 490
    // The paddingScaleFactor is used to adjust the padding of Dialog's
    // children.
491
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
492
    final TextDirection? textDirection = Directionality.maybeOf(context);
493

494 495 496
    Widget? titleWidget;
    Widget? contentWidget;
    Widget? actionsWidget;
497 498 499 500 501 502 503 504 505 506
    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,
        ),
507
        child: DefaultTextStyle(
508
          style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.headline6!,
509 510
          child: Semantics(
            child: title,
511
            namesRoute: label == null,
512 513 514 515
            container: true,
          ),
        ),
      );
516
    }
517

518 519
    if (content != null) {
      final EdgeInsets effectiveContentPadding = contentPadding.resolve(textDirection);
520
      contentWidget = Padding(
521 522 523 524 525 526
        padding: EdgeInsets.only(
          left: effectiveContentPadding.left * paddingScaleFactor,
          right: effectiveContentPadding.right * paddingScaleFactor,
          top: title == null ? effectiveContentPadding.top * paddingScaleFactor : effectiveContentPadding.top,
          bottom: effectiveContentPadding.bottom,
        ),
527
        child: DefaultTextStyle(
528
          style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subtitle1!,
529 530 531 532
          child: Semantics(
            container: true,
            child: content!,
          ),
533 534
        ),
      );
535 536
    }

537

538
    if (actions != null) {
539
      final double spacing = (buttonPadding?.horizontal ?? 16) / 2;
540 541
      actionsWidget = Padding(
        padding: actionsPadding,
542 543 544 545 546 547 548 549 550 551
        child: Container(
          alignment: AlignmentDirectional.centerEnd,
          padding: EdgeInsets.all(spacing),
          child: OverflowBar(
            spacing: spacing,
            overflowAlignment: OverflowBarAlignment.end,
            overflowDirection: actionsOverflowDirection ?? VerticalDirection.down,
            overflowSpacing: actionsOverflowButtonSpacing ?? 0,
            children: actions!,
          ),
552 553
        ),
      );
554
    }
555

556 557 558 559 560 561 562 563 564 565
    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>[
566 567
                  if (title != null) titleWidget!,
                  if (content != null) contentWidget!,
568 569 570 571 572
                ],
              ),
            ),
          ),
        if (actions != null)
573
          actionsWidget!,
574 575 576
      ];
    } else {
      columnChildren = <Widget>[
577 578 579
        if (title != null) titleWidget!,
        if (content != null) Flexible(child: contentWidget!),
        if (actions != null) actionsWidget!,
580 581 582
      ];
    }

583 584
    Widget dialogChild = IntrinsicWidth(
      child: Column(
585 586
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
587
        children: columnChildren,
588
      ),
589
    );
590 591

    if (label != null)
592
      dialogChild = Semantics(
593 594
        scopesRoute: true,
        explicitChildNodes: true,
595 596
        namesRoute: true,
        label: label,
597
        child: dialogChild,
598 599
      );

600 601 602
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
603 604
      insetPadding: insetPadding,
      clipBehavior: clipBehavior,
605 606 607
      shape: shape,
      child: dialogChild,
    );
608 609 610
  }
}

611 612 613 614 615 616 617
/// 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.
///
618 619 620 621 622 623
/// 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.
///
624
/// {@tool snippet}
625 626
///
/// ```dart
627
/// SimpleDialogOption(
628 629 630 631
///   onPressed: () { Navigator.pop(context, Department.treasury); },
///   child: const Text('Treasury department'),
/// )
/// ```
632
/// {@end-tool}
633
///
634 635 636 637
/// See also:
///
///  * [SimpleDialog], for a dialog in which to use this widget.
///  * [showDialog], which actually displays the dialog and returns its result.
638
///  * [TextButton], which are commonly used as actions in other kinds of
639
///    dialogs, such as [AlertDialog]s.
640
///  * <https://material.io/design/components/dialogs.html#simple-dialog>
641 642
class SimpleDialogOption extends StatelessWidget {
  /// Creates an option for a [SimpleDialog].
643
  const SimpleDialogOption({
644
    Key? key,
645
    this.onPressed,
646
    this.padding,
647 648 649 650 651 652
    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.
653 654 655
  ///
  /// When used in a [SimpleDialog], this will typically call [Navigator.pop]
  /// with a value for [showDialog] to complete its future with.
656
  final VoidCallback? onPressed;
657 658 659 660

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

663 664 665
  /// The amount of space to surround the [child] with.
  ///
  /// Defaults to EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0).
666
  final EdgeInsets? padding;
667

668 669
  @override
  Widget build(BuildContext context) {
670
    return InkWell(
671
      onTap: onPressed,
672
      child: Padding(
673
        padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
674
        child: child,
675 676 677 678 679
      ),
    );
  }
}

680 681 682 683 684
/// 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.
///
685 686 687 688
/// 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.
///
689 690 691 692 693 694
/// 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.
///
695 696
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/simple_dialog.mp4}
///
697
/// {@tool snippet}
698 699 700 701 702 703 704 705 706 707 708 709 710
///
/// 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
711
/// Future<void> _askedToLead() async {
712 713
///   switch (await showDialog<Department>(
///     context: context,
714
///     builder: (BuildContext context) {
715
///       return SimpleDialog(
716 717
///         title: const Text('Select assignment'),
///         children: <Widget>[
718
///           SimpleDialogOption(
719 720 721
///             onPressed: () { Navigator.pop(context, Department.treasury); },
///             child: const Text('Treasury department'),
///           ),
722
///           SimpleDialogOption(
723 724 725 726 727 728
///             onPressed: () { Navigator.pop(context, Department.state); },
///             child: const Text('State department'),
///           ),
///         ],
///       );
///     }
729 730 731 732 733 734 735 736
///   )) {
///     case Department.treasury:
///       // Let's go.
///       // ...
///     break;
///     case Department.state:
///       // ...
///     break;
737 738 739
///     case null:
///       // dialog dismissed
///     break;
740 741 742
///   }
/// }
/// ```
743
/// {@end-tool}
744
///
745 746
/// See also:
///
747
///  * [SimpleDialogOption], which are options used in this type of dialog.
748 749 750
///  * [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.
751
///  * <https://material.io/design/components/dialogs.html#simple-dialog>
752 753 754 755
class SimpleDialog extends StatelessWidget {
  /// Creates a simple dialog.
  ///
  /// Typically used in conjunction with [showDialog].
756 757
  ///
  /// The [titlePadding] and [contentPadding] arguments must not be null.
758
  const SimpleDialog({
759
    Key? key,
760
    this.title,
761
    this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
762
    this.titleTextStyle,
763
    this.children,
764
    this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
765 766
    this.backgroundColor,
    this.elevation,
767
    this.semanticLabel,
768 769
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
770
    this.shape,
771 772 773
  }) : assert(titlePadding != null),
       assert(contentPadding != null),
       super(key: key);
774 775 776 777 778

  /// The (optional) title of the dialog is displayed in a large font at the top
  /// of the dialog.
  ///
  /// Typically a [Text] widget.
779
  final Widget? title;
780 781 782

  /// Padding around the title.
  ///
783 784 785 786 787 788 789
  /// 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].
790
  final EdgeInsetsGeometry titlePadding;
791

792 793
  /// Style for the text in the [title] of this [SimpleDialog].
  ///
794
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
795
  /// [TextTheme.headline6] of [ThemeData.textTheme].
796
  final TextStyle? titleTextStyle;
797

798 799
  /// The (optional) content of the dialog is displayed in a
  /// [SingleChildScrollView] underneath the title.
800
  ///
801
  /// Typically a list of [SimpleDialogOption]s.
802
  final List<Widget>? children;
803 804 805

  /// Padding around the content.
  ///
806 807 808 809 810 811 812 813 814 815
  /// 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.
816
  final EdgeInsetsGeometry contentPadding;
817

818
  /// {@macro flutter.material.dialog.backgroundColor}
819
  final Color? backgroundColor;
820 821 822

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
823
  final double? elevation;
824

825
  /// The semantic label of the dialog used by accessibility frameworks to
826
  /// announce screen transitions when the dialog is opened and closed.
827
  ///
828
  /// If this label is not provided, a semantic label will be inferred from the
829 830
  /// [title] if it is not null.  If there is no title, the label will be taken
  /// from [MaterialLocalizations.dialogLabel].
831
  ///
832
  /// See also:
833
  ///
834
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
835
  ///    value is used.
836
  final String? semanticLabel;
837

838 839 840 841 842 843
  /// {@macro flutter.material.dialog.insetPadding}
  final EdgeInsets insetPadding;

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

844
  /// {@macro flutter.material.dialog.shape}
845
  final ShapeBorder? shape;
846

847 848
  @override
  Widget build(BuildContext context) {
849
    assert(debugCheckHasMaterialLocalizations(context));
850
    final ThemeData theme = Theme.of(context);
851

852
    String? label = semanticLabel;
853
    if (title == null) {
854
      switch (theme.platform) {
855
        case TargetPlatform.macOS:
856 857 858 859
        case TargetPlatform.iOS:
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
860 861
        case TargetPlatform.linux:
        case TargetPlatform.windows:
862
          label = semanticLabel ?? MaterialLocalizations.of(context).dialogLabel;
863
      }
864 865
    }

866 867
    // The paddingScaleFactor is used to adjust the padding of Dialog
    // children.
868
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
869
    final TextDirection? textDirection = Directionality.maybeOf(context);
870

871
    Widget? titleWidget;
872 873 874 875 876 877 878 879 880 881
    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(
882
          style: titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.headline6!,
883 884 885
          child: Semantics(
            namesRoute: label == null,
            container: true,
886
            child: title,
887
          ),
888 889 890 891
        ),
      );
    }

892
    Widget? contentWidget;
893 894 895 896 897 898 899 900 901 902
    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,
          ),
903
          child: ListBody(children: children!),
904 905 906 907
        ),
      );
    }

908
    Widget dialogChild = IntrinsicWidth(
909
      stepWidth: 56.0,
910
      child: ConstrainedBox(
911
        constraints: const BoxConstraints(minWidth: 280.0),
912
        child: Column(
913 914
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
915
          children: <Widget>[
916 917
            if (title != null) titleWidget!,
            if (children != null) contentWidget!,
918
          ],
919 920
        ),
      ),
921
    );
922 923

    if (label != null)
924
      dialogChild = Semantics(
925 926
        scopesRoute: true,
        explicitChildNodes: true,
927 928 929 930
        namesRoute: true,
        label: label,
        child: dialogChild,
      );
931 932 933
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
934 935
      insetPadding: insetPadding,
      clipBehavior: clipBehavior,
936 937 938
      shape: shape,
      child: dialogChild,
    );
939 940
  }
}
941

942
Widget _buildMaterialDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
943 944
  return FadeTransition(
    opacity: CurvedAnimation(
945 946 947 948 949
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: child,
  );
950 951
}

952 953 954
/// 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).
955
///
956
/// This function takes a `builder` which typically builds a [Dialog] widget.
957 958 959 960
/// 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.
961
///
962 963
/// The `child` argument is deprecated, and should be replaced with `builder`.
///
Ian Hickson's avatar
Ian Hickson committed
964 965 966 967
/// 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.
///
968 969 970 971
/// 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
972
/// barrier that darkens everything below the dialog. If `null` the default color
973 974 975 976
/// `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
977
/// (see [SafeArea] for more details). It is `true` by default, which means
978
/// the dialog will not overlap operating system areas. If it is set to `false`
979 980
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
981 982 983
/// 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
984
/// this method is pushed to the root navigator. It can not be `null`.
985
///
986 987 988
/// The `routeSettings` argument is passed to [showGeneralDialog],
/// see [RouteSettings] for details.
///
989 990
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
991
/// dialog rather than just `Navigator.pop(context, result)`.
992
///
993 994 995
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
996 997 998 999 1000 1001 1002 1003
/// ### State Restoration in Dialogs
///
/// Using this method will not enable state restoration for the dialog. In order
/// to enable state restoration for a dialog, use [Navigator.restorablePush]
/// or [Navigator.restorablePushNamed] with [DialogRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
1004
/// {@tool sample --template=stateless_widget_restoration_material}
1005 1006 1007 1008 1009 1010 1011 1012 1013
///
/// This sample demonstrates how to create a restorable Material dialog. This is
/// accomplished by enabling state restoration by specifying
/// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [DialogRoute] when the button is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
/// ```dart
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
/// Widget build(BuildContext context) {
///   return Scaffold(
///     body: Center(
///       child: OutlinedButton(
///         onPressed: () {
///           Navigator.of(context).restorablePush(_dialogBuilder);
///         },
///         child: const Text('Open Dialog'),
///       ),
///     ),
///   );
1025 1026
/// }
///
1027 1028 1029 1030 1031
/// static Route<Object?> _dialogBuilder(BuildContext context, Object? arguments) {
///   return DialogRoute<void>(
///     context: context,
///     builder: (BuildContext context) => const AlertDialog(title: Text('Material Alert!')),
///   );
1032 1033 1034 1035 1036
/// }
/// ```
///
/// {@end-tool}
///
1037
/// See also:
1038
///
1039 1040 1041
///  * [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.
1042
///  * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
1043 1044
///  * [showCupertinoDialog], which displays an iOS-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
1045
///  * <https://material.io/design/components/dialogs.html>
1046
Future<T?> showDialog<T>({
1047
  required BuildContext context,
1048
  required WidgetBuilder builder,
1049
  bool barrierDismissible = true,
1050 1051
  Color? barrierColor = Colors.black54,
  String? barrierLabel,
1052 1053
  bool useSafeArea = true,
  bool useRootNavigator = true,
1054
  RouteSettings? routeSettings,
1055
}) {
1056
  assert(builder != null);
1057 1058
  assert(barrierDismissible != null);
  assert(useSafeArea != null);
1059
  assert(useRootNavigator != null);
1060
  assert(debugCheckHasMaterialLocalizations(context));
1061

1062 1063 1064 1065 1066 1067 1068 1069 1070
  final CapturedThemes themes = InheritedTheme.capture(
    from: context,
    to: Navigator.of(
      context,
      rootNavigator: useRootNavigator,
    ).context,
  );

  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(DialogRoute<T>(
1071
    context: context,
1072 1073
    builder: builder,
    barrierColor: barrierColor,
1074
    barrierDismissible: barrierDismissible,
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    barrierLabel: barrierLabel,
    useSafeArea: useSafeArea,
    settings: routeSettings,
    themes: themes,
  ));
}

/// A dialog route with Material entrance and exit animations,
/// modal barrier color, and modal barrier behavior (dialog is dismissible
/// with a tap on the barrier).
///
/// It is used internally by [showDialog] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showDialog] for a state restoration app example.
///
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// 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.
///
/// The `context` argument is used to look up
/// [MaterialLocalizations.modalBarrierDismissLabel], which provides the
/// modal with a localized accessibility label that will be used for the
/// modal's barrier. However, a custom `barrierLabel` can be passed in as well.
///
/// The `barrierDismissible` argument is used to indicate whether tapping on the
/// barrier will dismiss the dialog. It is `true` by default and cannot be `null`.
///
/// The `barrierColor` argument is used to specify the color of the modal
/// barrier that darkens everything below the dialog. If `null`, the default
/// color `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
/// (see [SafeArea] for more details). It is `true` by default, which means
/// the dialog will not overlap operating system areas. If it is set to `false`
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
/// The `settings` argument define the settings for this route. See
/// [RouteSettings] for details.
///
/// See also:
///
///  * [showDialog], which is a way to display a DialogRoute.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
///  * [showCupertinoDialog], which displays an iOS-style dialog.
class DialogRoute<T> extends RawDialogRoute<T> {
  /// A dialog route with Material entrance and exit animations,
  /// modal barrier color, and modal barrier behavior (dialog is dismissible
  /// with a tap on the barrier).
  DialogRoute({
    required BuildContext context,
    required WidgetBuilder builder,
    CapturedThemes? themes,
    Color? barrierColor = Colors.black54,
    bool barrierDismissible = true,
    String? barrierLabel,
    bool useSafeArea = true,
    RouteSettings? settings,
  }) : assert(barrierDismissible != null),
       super(
         pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
           final Widget pageChild = Builder(builder: builder);
           Widget dialog = themes?.wrap(pageChild) ?? pageChild;
           if (useSafeArea) {
             dialog = SafeArea(child: dialog);
           }
           return dialog;
         },
         barrierDismissible: barrierDismissible,
         barrierColor: barrierColor,
         barrierLabel: barrierLabel ?? MaterialLocalizations.of(context).modalBarrierDismissLabel,
         transitionDuration: const Duration(milliseconds: 150),
         transitionBuilder: _buildMaterialDialogTransitions,
         settings: settings,
       );
1152
}
1153 1154 1155 1156 1157

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.
1158
  return lerpDouble(1.0, 1.0 / 3.0, clampedTextScaleFactor - 1.0)!;
1159
}