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

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

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

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

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

24
/// A material design dialog.
25
///
26 27 28 29
/// 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.
30 31
///
/// See also:
Ian Hickson's avatar
Ian Hickson committed
32
///
33 34 35
///  * [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.
36
///  * <https://material.io/design/components/dialogs.html>
37
class Dialog extends StatelessWidget {
38 39 40
  /// Creates a dialog.
  ///
  /// Typically used in conjunction with [showDialog].
41
  const Dialog({
42
    Key? key,
43 44
    this.backgroundColor,
    this.elevation,
45 46
    this.insetAnimationDuration = const Duration(milliseconds: 100),
    this.insetAnimationCurve = Curves.decelerate,
47 48
    this.insetPadding = _defaultInsetPadding,
    this.clipBehavior = Clip.none,
49
    this.shape,
50
    this.alignment,
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 120 121 122 123 124 125
  /// {@template flutter.material.dialog.alignment}
  /// How to align the [Dialog].
  ///
  /// If null, then [DialogTheme.alignment] is used. If that is also null, the
  /// default is [Alignment.center].
  /// {@endtemplate}
  final AlignmentGeometry? alignment;

126 127
  /// The widget below this widget in the tree.
  ///
128
  /// {@macro flutter.widgets.ProxyWidget.child}
129
  final Widget? child;
130

131
  static const RoundedRectangleBorder _defaultDialogShape =
132
    RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
133
  static const double _defaultElevation = 24.0;
134

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

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

  /// 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
281 282
  ///
  /// Typically a [Text] widget.
283
  final Widget? title;
284

285 286
  /// Padding around the title.
  ///
287 288 289 290 291 292 293 294
  /// 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].
295
  final EdgeInsetsGeometry? titlePadding;
296

297 298
  /// Style for the text in the [title] of this [AlertDialog].
  ///
299 300
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
  /// [TextTheme.headline6] of [ThemeData.textTheme].
301
  final TextStyle? titleTextStyle;
302

303 304
  /// 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
305
  ///
306 307 308 309
  /// 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.
310
  final Widget? content;
311

312 313
  /// Padding around the content.
  ///
314 315 316 317
  /// 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.
318
  final EdgeInsetsGeometry contentPadding;
319

320 321
  /// Style for the text in the [content] of this [AlertDialog].
  ///
322 323
  /// If null, [DialogTheme.contentTextStyle] is used. If that's null, defaults
  /// to [TextTheme.subtitle1] of [ThemeData.textTheme].
324
  final TextStyle? contentTextStyle;
325

326
  /// The (optional) set of actions that are displayed at the bottom of the
327
  /// dialog with an [OverflowBar].
Ian Hickson's avatar
Ian Hickson committed
328
  ///
329
  /// Typically this is a list of [TextButton] widgets. It is recommended to
330
  /// set the [Text.textAlign] to [TextAlign.end] for the [Text] within the
331
  /// [TextButton], so that buttons whose labels wrap to an extra line align
332
  /// with the overall [OverflowBar]'s alignment within the dialog.
333 334
  ///
  /// If the [title] is not null but the [content] _is_ null, then an extra 20
335
  /// pixels of padding is added above the [OverflowBar] to separate the [title]
336
  /// from the [actions].
337
  final List<Widget>? actions;
338

Dan Field's avatar
Dan Field committed
339
  /// Padding around the set of [actions] at the bottom of the dialog.
340 341 342 343 344 345 346 347 348
  ///
  /// 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.
  ///
349
  /// {@tool snippet}
350 351 352
  /// This is an example of a set of actions aligned with the content widget.
  /// ```dart
  /// AlertDialog(
353
  ///   title: const Text('Title'),
354 355
  ///   content: Container(width: 200, height: 200, color: Colors.green),
  ///   actions: <Widget>[
356 357
  ///     ElevatedButton(onPressed: () {}, child: const Text('Button 1')),
  ///     ElevatedButton(onPressed: () {}, child: const Text('Button 2')),
358
  ///   ],
359
  ///   actionsPadding: const EdgeInsets.symmetric(horizontal: 8.0),
360 361 362
  /// )
  /// ```
  /// {@end-tool}
363 364 365
  ///
  /// See also:
  ///
366
  /// * [OverflowBar], which [actions] configures to lay itself out.
367 368
  final EdgeInsetsGeometry actionsPadding;

369 370 371 372 373 374 375 376 377
  /// Defines the horizontal layout of the [actions] according to the same
  /// rules as for [Row.mainAxisAlignment].
  ///
  /// This parameter is passed along to the dialog's [OverflowBar].
  ///
  /// If this parameter is null (the default) then [MainAxisAlignment.end]
  /// is used.
  final MainAxisAlignment? actionsAlignment;

378 379 380 381 382 383 384 385 386 387 388 389 390
  /// 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.
  ///
  /// See also:
  ///
391
  /// * [OverflowBar], which [actions] configures to lay itself out.
392
  final VerticalDirection? actionsOverflowDirection;
393

394 395
  /// The spacing between [actions] when the [OverflowBar] switches
  /// to a column layout because the actions don't fit horizontally.
396 397 398 399 400 401 402 403 404 405 406 407 408
  ///
  /// 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.
409
  final double? actionsOverflowButtonSpacing;
410

411 412 413 414 415
  /// 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.
  ///
416
  /// If this property is null, then it will default to
417
  /// 8.0 logical pixels on the left and right.
418
  final EdgeInsetsGeometry? buttonPadding;
419

420
  /// {@macro flutter.material.dialog.backgroundColor}
421
  final Color? backgroundColor;
422 423 424

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
425
  final double? elevation;
426

427
  /// The semantic label of the dialog used by accessibility frameworks to
428
  /// announce screen transitions when the dialog is opened and closed.
429
  ///
430 431 432 433 434
  /// 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.
435
  ///
436
  /// See also:
437
  ///
438
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
439
  ///    value is used.
440
  final String? semanticLabel;
441

442 443 444 445 446 447
  /// {@macro flutter.material.dialog.insetPadding}
  final EdgeInsets insetPadding;

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

448
  /// {@macro flutter.material.dialog.shape}
449
  final ShapeBorder? shape;
450

451
  /// {@macro flutter.material.dialog.alignment}
452 453
  final AlignmentGeometry? alignment;

454 455 456 457 458 459 460 461 462
  /// 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;

463
  @override
464
  Widget build(BuildContext context) {
465
    assert(debugCheckHasMaterialLocalizations(context));
466
    final ThemeData theme = Theme.of(context);
467
    final DialogTheme dialogTheme = DialogTheme.of(context);
468

469
    String? label = semanticLabel;
470 471 472 473 474 475 476 477
    switch (theme.platform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
478
        label ??= MaterialLocalizations.of(context).alertDialogLabel;
479 480
    }

481 482
    // The paddingScaleFactor is used to adjust the padding of Dialog's
    // children.
483
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
484
    final TextDirection? textDirection = Directionality.maybeOf(context);
485

486 487 488
    Widget? titleWidget;
    Widget? contentWidget;
    Widget? actionsWidget;
489 490 491 492 493 494 495 496 497 498
    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,
        ),
499
        child: DefaultTextStyle(
500
          style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.headline6!,
501
          child: Semantics(
502 503 504
            // For iOS platform, the focus always lands on the title.
            // Set nameRoute to false to avoid title being announce twice.
            namesRoute: label == null && theme.platform != TargetPlatform.iOS,
505
            container: true,
506
            child: title,
507 508 509
          ),
        ),
      );
510
    }
511

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

    if (actions != null) {
532
      final double spacing = (buttonPadding?.horizontal ?? 16) / 2;
533
      actionsWidget = Padding(
534 535 536 537 538 539 540 541
        padding: actionsPadding.add(EdgeInsets.all(spacing)),
        child: OverflowBar(
          alignment: actionsAlignment ?? MainAxisAlignment.end,
          spacing: spacing,
          overflowAlignment: OverflowBarAlignment.end,
          overflowDirection: actionsOverflowDirection ?? VerticalDirection.down,
          overflowSpacing: actionsOverflowButtonSpacing ?? 0,
          children: actions!,
542 543
        ),
      );
544
    }
545

546 547 548 549 550 551 552 553 554 555
    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>[
556 557
                  if (title != null) titleWidget!,
                  if (content != null) contentWidget!,
558 559 560 561 562
                ],
              ),
            ),
          ),
        if (actions != null)
563
          actionsWidget!,
564 565 566
      ];
    } else {
      columnChildren = <Widget>[
567 568 569
        if (title != null) titleWidget!,
        if (content != null) Flexible(child: contentWidget!),
        if (actions != null) actionsWidget!,
570 571 572
      ];
    }

573 574
    Widget dialogChild = IntrinsicWidth(
      child: Column(
575 576
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
577
        children: columnChildren,
578
      ),
579
    );
580 581

    if (label != null)
582
      dialogChild = Semantics(
583 584
        scopesRoute: true,
        explicitChildNodes: true,
585 586
        namesRoute: true,
        label: label,
587
        child: dialogChild,
588 589
      );

590 591 592
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
593 594
      insetPadding: insetPadding,
      clipBehavior: clipBehavior,
595
      shape: shape,
596
      alignment: alignment,
597 598
      child: dialogChild,
    );
599 600 601
  }
}

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

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

654 655 656
  /// The amount of space to surround the [child] with.
  ///
  /// Defaults to EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0).
657
  final EdgeInsets? padding;
658

659 660
  @override
  Widget build(BuildContext context) {
661
    return InkWell(
662
      onTap: onPressed,
663
      child: Padding(
664
        padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
665
        child: child,
666 667 668 669 670
      ),
    );
  }
}

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

  /// The (optional) title of the dialog is displayed in a large font at the top
  /// of the dialog.
  ///
  /// Typically a [Text] widget.
771
  final Widget? title;
772 773 774

  /// Padding around the title.
  ///
775 776 777 778 779 780 781
  /// 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].
782
  final EdgeInsetsGeometry titlePadding;
783

784 785
  /// Style for the text in the [title] of this [SimpleDialog].
  ///
786
  /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
787
  /// [TextTheme.headline6] of [ThemeData.textTheme].
788
  final TextStyle? titleTextStyle;
789

790 791
  /// The (optional) content of the dialog is displayed in a
  /// [SingleChildScrollView] underneath the title.
792
  ///
793
  /// Typically a list of [SimpleDialogOption]s.
794
  final List<Widget>? children;
795 796 797

  /// Padding around the content.
  ///
798 799 800 801 802 803 804 805 806 807
  /// 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.
808
  final EdgeInsetsGeometry contentPadding;
809

810
  /// {@macro flutter.material.dialog.backgroundColor}
811
  final Color? backgroundColor;
812 813 814

  /// {@macro flutter.material.dialog.elevation}
  /// {@macro flutter.material.material.elevation}
815
  final double? elevation;
816

817
  /// The semantic label of the dialog used by accessibility frameworks to
818
  /// announce screen transitions when the dialog is opened and closed.
819
  ///
820
  /// If this label is not provided, a semantic label will be inferred from the
821 822
  /// [title] if it is not null.  If there is no title, the label will be taken
  /// from [MaterialLocalizations.dialogLabel].
823
  ///
824
  /// See also:
825
  ///
826
  ///  * [SemanticsConfiguration.namesRoute], for a description of how this
827
  ///    value is used.
828
  final String? semanticLabel;
829

830 831 832 833 834 835
  /// {@macro flutter.material.dialog.insetPadding}
  final EdgeInsets insetPadding;

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

836
  /// {@macro flutter.material.dialog.shape}
837
  final ShapeBorder? shape;
838

839 840 841
  /// {@macro flutter.material.dialog.shape}
  final AlignmentGeometry? alignment;

842 843
  @override
  Widget build(BuildContext context) {
844
    assert(debugCheckHasMaterialLocalizations(context));
845
    final ThemeData theme = Theme.of(context);
846

847
    String? label = semanticLabel;
848 849 850 851 852 853 854 855 856
    switch (theme.platform) {
      case TargetPlatform.macOS:
      case TargetPlatform.iOS:
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        label ??= MaterialLocalizations.of(context).dialogLabel;
857 858
    }

859 860
    // The paddingScaleFactor is used to adjust the padding of Dialog
    // children.
861
    final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor);
862
    final TextDirection? textDirection = Directionality.maybeOf(context);
863

864
    Widget? titleWidget;
865 866 867 868 869 870 871 872 873 874
    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(
875
          style: titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.headline6!,
876
          child: Semantics(
877 878 879
            // For iOS platform, the focus always lands on the title.
            // Set nameRoute to false to avoid title being announce twice.
            namesRoute: label == null && theme.platform != TargetPlatform.iOS,
880
            container: true,
881
            child: title,
882
          ),
883 884 885 886
        ),
      );
    }

887
    Widget? contentWidget;
888 889 890 891 892 893 894 895 896 897
    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,
          ),
898
          child: ListBody(children: children!),
899 900 901 902
        ),
      );
    }

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

    if (label != null)
919
      dialogChild = Semantics(
920 921
        scopesRoute: true,
        explicitChildNodes: true,
922 923 924 925
        namesRoute: true,
        label: label,
        child: dialogChild,
      );
926 927 928
    return Dialog(
      backgroundColor: backgroundColor,
      elevation: elevation,
929 930
      insetPadding: insetPadding,
      clipBehavior: clipBehavior,
931
      shape: shape,
932
      alignment: alignment,
933 934
      child: dialogChild,
    );
935 936
  }
}
937

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

948 949 950
/// 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).
951
///
952
/// This function takes a `builder` which typically builds a [Dialog] widget.
953 954 955 956
/// 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.
957
///
Ian Hickson's avatar
Ian Hickson committed
958 959 960 961
/// 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.
///
962 963 964 965
/// 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
966
/// barrier that darkens everything below the dialog. If `null` the default color
967 968 969 970
/// `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
971
/// (see [SafeArea] for more details). It is `true` by default, which means
972
/// the dialog will not overlap operating system areas. If it is set to `false`
973 974
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
975 976 977
/// 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
978
/// this method is pushed to the root navigator. It can not be `null`.
979
///
980 981 982
/// The `routeSettings` argument is passed to [showGeneralDialog],
/// see [RouteSettings] for details.
///
983 984
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
985
/// dialog rather than just `Navigator.pop(context, result)`.
986
///
987 988 989
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
990 991 992 993 994 995 996 997
/// ### 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].
///
998
/// {@tool sample}
999 1000 1001 1002 1003 1004 1005
/// 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}
///
1006
/// ** See code in examples/api/lib/material/dialog/show_dialog.0.dart **
1007 1008
/// {@end-tool}
///
1009
/// See also:
1010
///
1011 1012 1013
///  * [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.
1014
///  * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
1015 1016
///  * [showCupertinoDialog], which displays an iOS-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
1017
///  * <https://material.io/design/components/dialogs.html>
1018
Future<T?> showDialog<T>({
1019
  required BuildContext context,
1020
  required WidgetBuilder builder,
1021
  bool barrierDismissible = true,
1022 1023
  Color? barrierColor = Colors.black54,
  String? barrierLabel,
1024 1025
  bool useSafeArea = true,
  bool useRootNavigator = true,
1026
  RouteSettings? routeSettings,
1027
}) {
1028
  assert(builder != null);
1029 1030
  assert(barrierDismissible != null);
  assert(useSafeArea != null);
1031
  assert(useRootNavigator != null);
1032
  assert(debugCheckHasMaterialLocalizations(context));
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042
  final CapturedThemes themes = InheritedTheme.capture(
    from: context,
    to: Navigator.of(
      context,
      rootNavigator: useRootNavigator,
    ).context,
  );

  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(DialogRoute<T>(
1043
    context: context,
1044 1045
    builder: builder,
    barrierColor: barrierColor,
1046
    barrierDismissible: barrierDismissible,
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 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
    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,
       );
1124
}
1125 1126

double _paddingScaleFactor(double textScaleFactor) {
1127
  final double clampedTextScaleFactor = textScaleFactor.clamp(1.0, 2.0);
1128 1129
  // 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.
1130
  return lerpDouble(1.0, 1.0 / 3.0, clampedTextScaleFactor - 1.0)!;
1131
}