dialog.dart 21.2 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:ui';
7

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

11
import 'button_bar.dart';
12
import 'button_theme.dart';
13
import 'colors.dart';
14
import 'ink_well.dart';
15
import 'material.dart';
16
import 'material_localizations.dart';
17
import 'theme.dart';
18

19 20 21
// Examples can assume:
// enum Department { treasury, state }

22
/// A material design dialog.
23
///
24 25 26 27
/// 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.
28 29
///
/// See also:
Ian Hickson's avatar
Ian Hickson committed
30
///
31 32 33
///  * [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.
34
///  * <https://material.google.com/components/dialogs.html>
35
class Dialog extends StatelessWidget {
36 37 38
  /// Creates a dialog.
  ///
  /// Typically used in conjunction with [showDialog].
39
  const Dialog({
40 41
    Key key,
    this.child,
42 43
    this.insetAnimationDuration = const Duration(milliseconds: 100),
    this.insetAnimationCurve = Curves.decelerate,
44 45
  }) : super(key: key);

46
  /// The widget below this widget in the tree.
47 48
  ///
  /// {@macro flutter.widgets.child}
49 50
  final Widget child;

51 52 53 54 55 56 57 58 59 60 61 62
  /// 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.
  final Duration insetAnimationDuration;

  /// The curve to use for the animation shown when the system keyboard intrudes
  /// into the space that the dialog is placed in.
  ///
  /// Defaults to [Curves.fastOutSlowIn].
  final Curve insetAnimationCurve;

63
  Color _getColor(BuildContext context) {
64
    return Theme.of(context).dialogBackgroundColor;
65 66 67 68
  }

  @override
  Widget build(BuildContext context) {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    return new AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
      duration: insetAnimationDuration,
      curve: insetAnimationCurve,
      child: new MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: new Center(
          child: new ConstrainedBox(
            constraints: const BoxConstraints(minWidth: 280.0),
            child: new Material(
              elevation: 24.0,
              color: _getColor(context),
              type: MaterialType.card,
              child: child,
            ),
          ),
        ),
      ),
91 92 93 94 95 96 97 98 99 100 101 102 103
    );
  }
}

/// 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.
///
/// 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. Consider
104
/// using a scrolling widget, such as [ListView], for [content] to avoid
105
/// overflow.
106 107 108 109 110 111 112
///
/// 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.
///
113 114 115 116 117 118 119 120 121 122
/// ## Sample code
///
/// 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
/// Future<Null> _neverSatisfied() async {
///   return showDialog<Null>(
///     context: context,
///     barrierDismissible: false, // user must tap button!
123 124 125 126 127 128 129 130 131 132
///     builder: (BuildContext context) {
///       return new AlertDialog(
///         title: new Text('Rewind and remember'),
///         content: new SingleChildScrollView(
///           child: new ListBody(
///             children: <Widget>[
///               new Text('You will never be satisfied.'),
///               new Text('You\’re like me. I’m never satisfied.'),
///             ],
///           ),
133
///         ),
134 135 136 137 138 139 140 141 142 143
///         actions: <Widget>[
///           new FlatButton(
///             child: new Text('Regret'),
///             onPressed: () {
///               Navigator.of(context).pop();
///             },
///           ),
///         ],
///       );
///     },
144 145 146 147
///   );
/// }
/// ```
///
148 149
/// See also:
///
150 151 152
///  * [SimpleDialog], which handles the scrolling of the contents but has no [actions].
///  * [Dialog], on which [AlertDialog] and [SimpleDialog] are based.
///  * [showDialog], which actually displays the dialog and returns its result.
153 154 155 156 157
///  * <https://material.google.com/components/dialogs.html#dialogs-alerts>
class AlertDialog extends StatelessWidget {
  /// Creates an alert dialog.
  ///
  /// Typically used in conjunction with [showDialog].
158 159 160 161
  ///
  /// 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.
162
  const AlertDialog({
163
    Key key,
164
    this.title,
165
    this.titlePadding,
166
    this.content,
167
    this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
168
    this.actions,
169
    this.semanticLabel,
170 171
  }) : assert(contentPadding != null),
       super(key: key);
172 173 174

  /// 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
175 176
  ///
  /// Typically a [Text] widget.
177 178
  final Widget title;

179 180
  /// Padding around the title.
  ///
181 182 183 184 185 186 187 188
  /// 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].
189
  final EdgeInsetsGeometry titlePadding;
190

191 192
  /// 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
193
  ///
194 195
  /// Typically, this is a [ListView] containing the contents of the dialog.
  /// Using a [ListView] ensures that the contents can scroll if they are too
196
  /// big to fit on the display.
197 198
  final Widget content;

199 200
  /// Padding around the content.
  ///
201 202 203 204
  /// 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.
205
  final EdgeInsetsGeometry contentPadding;
206

207 208
  /// The (optional) set of actions that are displayed at the bottom of the
  /// dialog.
Ian Hickson's avatar
Ian Hickson committed
209 210 211
  ///
  /// Typically this is a list of [FlatButton] widgets.
  ///
212 213 214 215 216 217
  /// 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].
218 219
  final List<Widget> actions;

220
  /// The semantic label of the dialog used by accessibility frameworks to
221
  /// announce screen transitions when the dialog is opened and closed.
222
  ///
223 224 225
  /// If this label is not provided, a semantic label will be infered from the
  /// [title] if it is not null.  If there is no title, the label will be taken
  /// from [MaterialLocalizations.alertDialogLabel].
226
  ///
227
  /// See also:
228
  ///
229 230 231 232
  ///  * [SemanticsConfiguration.isRouteName], for a description of how this
  ///    value is used.
  final String semanticLabel;

233
  @override
234
  Widget build(BuildContext context) {
235
    final List<Widget> children = <Widget>[];
236
    String label = semanticLabel;
237 238

    if (title != null) {
239
      children.add(new Padding(
240
        padding: titlePadding ?? new EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0),
241
        child: new DefaultTextStyle(
242
          style: Theme.of(context).textTheme.title,
243
          child: new Semantics(child: title, namesRoute: true),
244
        ),
245
      ));
246 247 248 249 250 251 252 253 254
    } else {
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
          label = semanticLabel;
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
          label = semanticLabel ?? MaterialLocalizations.of(context)?.alertDialogLabel;
      }
255 256 257
    }

    if (content != null) {
258
      children.add(new Flexible(
259
        child: new Padding(
260
          padding: contentPadding,
261 262
          child: new DefaultTextStyle(
            style: Theme.of(context).textTheme.subhead,
263 264 265
            child: content,
          ),
        ),
266 267 268
      ));
    }

269
    if (actions != null) {
270
      children.add(new ButtonTheme.bar(
271
        child: new ButtonBar(
272 273
          children: actions,
        ),
274
      ));
275
    }
276

277 278 279 280 281
    Widget dialogChild = new IntrinsicWidth(
      child: new Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: children,
282
      ),
283
    );
284 285 286 287 288 289 290 291 292

    if (label != null)
      dialogChild = new Semantics(
        namesRoute: true,
        label: label,
        child: dialogChild
      );

    return new Dialog(child: dialogChild);
293 294 295
  }
}

296 297 298 299 300 301 302
/// 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.
///
303 304 305 306 307 308
/// 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.
///
309 310 311 312 313 314 315 316 317
/// ## Sample code
///
/// ```dart
/// new SimpleDialogOption(
///   onPressed: () { Navigator.pop(context, Department.treasury); },
///   child: const Text('Treasury department'),
/// )
/// ```
///
318 319 320 321 322 323 324 325 326
/// See also:
///
///  * [SimpleDialog], for a dialog in which to use this widget.
///  * [showDialog], which actually displays the dialog and returns its result.
///  * [FlatButton], which are commonly used as actions in other kinds of
///    dialogs, such as [AlertDialog]s.
///  * <https://material.google.com/components/dialogs.html#dialogs-simple-dialogs>
class SimpleDialogOption extends StatelessWidget {
  /// Creates an option for a [SimpleDialog].
327
  const SimpleDialogOption({
328 329 330 331 332 333 334 335
    Key key,
    this.onPressed,
    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.
336 337 338
  ///
  /// When used in a [SimpleDialog], this will typically call [Navigator.pop]
  /// with a value for [showDialog] to complete its future with.
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  final VoidCallback onPressed;

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

  @override
  Widget build(BuildContext context) {
    return new InkWell(
      onTap: onPressed,
      child: new Padding(
        padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
        child: child
      ),
    );
  }
}

358 359 360 361 362
/// 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.
///
363 364 365 366
/// 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.
///
367 368 369 370 371 372
/// 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.
///
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
/// ## Sample code
///
/// 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
/// Future<Null> _askedToLead() async {
///   switch (await showDialog<Department>(
///     context: context,
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
///     builder: (BuildContext context) {
///       return new SimpleDialog(
///         title: const Text('Select assignment'),
///         children: <Widget>[
///           new SimpleDialogOption(
///             onPressed: () { Navigator.pop(context, Department.treasury); },
///             child: const Text('Treasury department'),
///           ),
///           new SimpleDialogOption(
///             onPressed: () { Navigator.pop(context, Department.state); },
///             child: const Text('State department'),
///           ),
///         ],
///       );
///     }
405 406 407 408 409 410 411 412 413 414 415 416
///   )) {
///     case Department.treasury:
///       // Let's go.
///       // ...
///     break;
///     case Department.state:
///       // ...
///     break;
///   }
/// }
/// ```
///
417 418
/// See also:
///
419
///  * [SimpleDialogOption], which are options used in this type of dialog.
420 421 422
///  * [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.
423 424 425 426 427
///  * <https://material.google.com/components/dialogs.html#dialogs-simple-dialogs>
class SimpleDialog extends StatelessWidget {
  /// Creates a simple dialog.
  ///
  /// Typically used in conjunction with [showDialog].
428 429
  ///
  /// The [titlePadding] and [contentPadding] arguments must not be null.
430
  const SimpleDialog({
431 432
    Key key,
    this.title,
433
    this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
434
    this.children,
435
    this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
436
    this.semanticLabel,
437 438 439
  }) : assert(titlePadding != null),
       assert(contentPadding != null),
       super(key: key);
440 441 442 443 444 445 446 447 448

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

  /// Padding around the title.
  ///
449 450 451 452 453 454 455
  /// 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].
456
  final EdgeInsetsGeometry titlePadding;
457

458 459
  /// The (optional) content of the dialog is displayed in a
  /// [SingleChildScrollView] underneath the title.
460
  ///
461
  /// Typically a list of [SimpleDialogOption]s.
462 463 464 465
  final List<Widget> children;

  /// Padding around the content.
  ///
466 467 468 469 470 471 472 473 474 475
  /// 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.
476
  final EdgeInsetsGeometry contentPadding;
477

478
  /// The semantic label of the dialog used by accessibility frameworks to
479
  /// announce screen transitions when the dialog is opened and closed.
480
  ///
481 482 483
  /// If this label is not provided, a semantic label will be infered from the
  /// [title] if it is not null.  If there is no title, the label will be taken
  /// from [MaterialLocalizations.dialogLabel].
484
  ///
485
  /// See also:
486
  ///
487 488 489 490
  ///  * [SemanticsConfiguration.isRouteName], for a description of how this
  ///    value is used.
  final String semanticLabel;

491 492 493
  @override
  Widget build(BuildContext context) {
    final List<Widget> body = <Widget>[];
494
    String label = semanticLabel;
495 496 497

    if (title != null) {
      body.add(new Padding(
498
        padding: titlePadding,
499 500
        child: new DefaultTextStyle(
          style: Theme.of(context).textTheme.title,
501
          child: new Semantics(namesRoute: true, child: title),
502 503
        )
      ));
504 505 506 507 508 509 510 511 512
    } else {
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
          label = semanticLabel;
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
          label = semanticLabel ?? MaterialLocalizations.of(context)?.dialogLabel;
      }
513 514 515 516
    }

    if (children != null) {
      body.add(new Flexible(
517
        child: new SingleChildScrollView(
518
          padding: contentPadding,
519
          child: new ListBody(children: children),
520 521 522 523
        )
      ));
    }

524 525 526 527 528 529 530 531 532 533
    Widget dialogChild = new IntrinsicWidth(
      stepWidth: 56.0,
      child: new ConstrainedBox(
        constraints: const BoxConstraints(minWidth: 280.0),
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: body,
        ),
      ),
534
    );
535 536 537 538 539 540 541 542

    if (label != null)
      dialogChild = new Semantics(
        namesRoute: true,
        label: label,
        child: dialogChild,
      );
    return new Dialog(child: dialogChild);
543 544
  }
}
545

546 547 548 549 550 551 552 553
Widget _buildMaterialDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
  return new FadeTransition(
    opacity: new CurvedAnimation(
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: child,
  );
554 555
}

556 557 558
/// 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).
559
///
560
/// This function takes a `builder` which typically builds a [Dialog] widget.
561 562 563 564
/// 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.
565
///
Ian Hickson's avatar
Ian Hickson committed
566 567 568 569
/// 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.
///
570 571
/// The `child` argument is deprecated, and should be replaced with `builder`.
///
572
/// Returns a [Future] that resolves to the value (if any) that was passed to
573 574
/// [Navigator.pop] when the dialog was closed.
///
575 576 577
/// The dialog route created by this method is pushed to the root navigator.
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
578
/// dialog rather than just `Navigator.pop(context, result)`.
579
///
580
/// See also:
581 582 583
///  * [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.
584
///  * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
585 586
///  * [showCupertinoDialog], which displays an iOS-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
587
///  * <https://material.google.com/components/dialogs.html>
588
Future<T> showDialog<T>({
589
  @required BuildContext context,
590
  bool barrierDismissible = true,
591 592 593 594 595 596
  @Deprecated(
    'Instead of using the "child" argument, return the child from a closure '
    'provided to the "builder" argument. This will ensure that the BuildContext '
    'is appropriate for widgets built in the dialog.'
  ) Widget child,
  WidgetBuilder builder,
597
}) {
598
  assert(child == null || builder == null);
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
      final ThemeData theme = Theme.of(context, shadowThemeOnly: true);
      final Widget pageChild =  child ?? new Builder(builder: builder);
      return new SafeArea(
        child: new Builder(
          builder: (BuildContext context) {
            return theme != null
                ? new Theme(data: theme, child: pageChild)
                : pageChild;
          }
        ),
      );
    },
614
    barrierDismissible: barrierDismissible,
615
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
616 617 618 619 620
    barrierColor: Colors.black54,
    transitionDuration: const Duration(milliseconds: 150),
    transitionBuilder: _buildMaterialDialogTransitions,
  );
}