snack_bar.dart 9.31 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 'package:flutter/foundation.dart';
6
import 'package:flutter/widgets.dart';
7

8
import 'button.dart';
9
import 'flat_button.dart';
10
import 'material.dart';
11
import 'scaffold.dart';
12
import 'theme.dart';
13
import 'theme_data.dart';
Matt Perry's avatar
Matt Perry committed
14

15
// https://material.google.com/components/snackbars-toasts.html#snackbars-toasts-specs
16
const double _kSnackBarPadding = 24.0;
Hixie's avatar
Hixie committed
17
const double _kSingleLineVerticalPadding = 14.0;
18 19
const double _kMultiLineVerticalTopPadding = 24.0;
const double _kMultiLineVerticalSpaceBetweenTextAndButtons = 10.0;
20
const Color _kSnackBackground = const Color(0xFF323232);
Matt Perry's avatar
Matt Perry committed
21

Hixie's avatar
Hixie committed
22 23 24 25 26 27
// TODO(ianh): We should check if the given text and actions are going to fit on
// one line or not, and if they are, use the single-line layout, and if not, use
// the multiline layout. See link above.

// TODO(ianh): Implement the Tablet version of snackbar if we're "on a tablet".

28
const Duration _kSnackBarTransitionDuration = const Duration(milliseconds: 250);
29
const Duration _kSnackBarDisplayDuration = const Duration(milliseconds: 1500);
30
const Curve _snackBarHeightCurve = Curves.fastOutSlowIn;
31
const Curve _snackBarFadeCurve = const Interval(0.72, 1.0, curve: Curves.fastOutSlowIn);
Hixie's avatar
Hixie committed
32

33 34
/// Specify how a [SnackBar] was closed.
///
35 36 37 38
/// The [ScaffoldState.showSnackBar] function returns a
/// [ScaffoldFeatureController]. The value of the controller's closed property
/// is a Future that resolves to a SnackBarClosedReason. Applications that need
/// to know how a snackbar was closed can use this value.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
///
/// Example:
///
/// ```dart
/// Scaffold.of(context).showSnackBar(
///   new SnackBar( ... )
/// ).closed.then((SnackBarClosedReason reason) {
///    ...
/// });
/// ```
enum SnackBarClosedReason {
  /// The snack bar was closed after the user tapped a [SnackBarAction].
  action,

  /// The snack bar was closed by a user's swipe.
  swipe,

  /// The snack bar was closed by the [ScaffoldFeatureController] close callback
57
  /// or by calling [ScaffoldState.hideCurrentSnackBar] directly.
58 59
  hide,

60
  /// The snack bar was closed by an call to [ScaffoldState.removeCurrentSnackBar].
61 62 63 64 65 66
  remove,

  /// The snack bar was closed because its timer expired.
  timeout,
}

67 68 69 70 71
/// A button for a [SnackBar], known as an "action".
///
/// Snack bar actions are always enabled. If you want to disable a snack bar
/// action, simply don't include it in the snack bar.
///
72 73
/// Snack bar actions can only be pressed once. Subsequent presses are ignored.
///
74 75 76
/// See also:
///
///  * [SnackBar]
77
///  * <https://material.google.com/components/snackbars-toasts.html>
78
class SnackBarAction extends StatefulWidget {
79 80 81
  /// Creates an action for a [SnackBar].
  ///
  /// The [label] and [onPressed] arguments must be non-null.
82
  const SnackBarAction({
83
    Key key,
84
    @required this.label,
85
    @required this.onPressed
86 87 88
  }) : assert(label != null),
       assert(onPressed != null),
       super(key: key);
89

90
  /// The button label.
91
  final String label;
92

93
  /// The callback to be called when the button is pressed. Must not be null.
94
  ///
95
  /// This callback will be called at most once each time this action is
96
  /// displayed in a [SnackBar].
97
  final VoidCallback onPressed;
98

99 100 101 102 103 104 105 106 107 108 109 110 111
  @override
  _SnackBarActionState createState() => new _SnackBarActionState();
}

class _SnackBarActionState extends State<SnackBarAction> {
  bool _haveTriggeredAction = false;

  void _handlePressed() {
    if (_haveTriggeredAction)
      return;
    setState(() {
      _haveTriggeredAction = true;
    });
112
    widget.onPressed();
113
    Scaffold.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.action);
114 115
  }

116
  @override
Hixie's avatar
Hixie committed
117
  Widget build(BuildContext context) {
118 119
    return new FlatButton(
      onPressed: _haveTriggeredAction ? null : _handlePressed,
120
      child: new Text(widget.label)
121 122 123
    );
  }
}
124

125 126 127
/// A lightweight message with an optional action which briefly displays at the
/// bottom of the screen.
///
128 129 130 131
/// To display a snack bar, call `Scaffold.of(context).showSnackBar()`, passing
/// an instance of [SnackBar] that describes the message.
///
/// To control how long the [SnackBar] remains visible, specify a [duration].
132 133
///
/// See also:
134
///
135 136 137 138 139 140 141
///  * [Scaffold.of], to obtain the current [ScaffoldState], which manages the
///    display and animation of snack bars.
///  * [ScaffoldState.showSnackBar], which displays a [SnackBar].
///  * [ScaffoldState.removeCurrentSnackBar], which abruptly hides the currently
///    displayed snack bar, if any, and allows the next to be displayed.
///  * [SnackBarAction], which is used to specify an [action] button to show
///    on the snack bar.
142
///  * <https://material.google.com/components/snackbars-toasts.html>
143
class SnackBar extends StatelessWidget {
144 145 146
  /// Creates a snack bar.
  ///
  /// The [content] argument must be non-null.
147
  const SnackBar({
148
    Key key,
149
    @required this.content,
150
    this.backgroundColor,
151
    this.action,
152
    this.duration: _kSnackBarDisplayDuration,
153
    this.animation,
154 155
  }) : assert(content != null),
       super(key: key);
156

157 158 159
  /// The primary content of the snack bar.
  ///
  /// Typically a [Text] widget.
160
  final Widget content;
161

162 163 164
  /// The Snackbar's background color. By default the color is dark grey.
  final Color backgroundColor;

165 166 167 168
  /// (optional) An action that the user can take based on the snack bar.
  ///
  /// For example, the snack bar might let the user undo the operation that
  /// prompted the snackbar. Snack bars can have at most one action.
169 170
  ///
  /// The action should not be "dismiss" or "cancel".
171
  final SnackBarAction action;
172 173

  /// The amount of time the snack bar should be displayed.
174 175 176 177 178 179 180 181 182
  ///
  /// Defaults to 1.5s.
  ///
  /// See also:
  ///
  ///  * [ScaffoldState.removeCurrentSnackBar], which abruptly hides the
  ///    currently displayed snack bar, if any, and allows the next to be
  ///    displayed.
  ///  * <https://material.google.com/components/snackbars-toasts.html>
Hixie's avatar
Hixie committed
183
  final Duration duration;
184 185

  /// The animation driving the entrance and exit of the snack bar.
186
  final Animation<double> animation;
187

188
  @override
189
  Widget build(BuildContext context) {
190
    assert(animation != null);
191 192
    final ThemeData theme = Theme.of(context);
    final ThemeData darkTheme = new ThemeData(
193 194 195 196
      brightness: Brightness.dark,
      accentColor: theme.accentColor,
      accentColorBrightness: theme.accentColorBrightness
    );
197
    final List<Widget> children = <Widget>[
198
      const SizedBox(width: _kSnackBarPadding),
199
      new Expanded(
200
        child: new Container(
201
          padding: const EdgeInsets.symmetric(vertical: _kSingleLineVerticalPadding),
202
          child: new DefaultTextStyle(
203
            style: darkTheme.textTheme.subhead,
204
            child: content,
205 206 207
          )
        )
      )
208
    ];
209 210 211 212 213 214 215 216 217
    if (action != null) {
      children.add(new ButtonTheme.bar(
        padding: const EdgeInsets.symmetric(horizontal: _kSnackBarPadding),
        textTheme: ButtonTextTheme.accent,
        child: action
      ));
    } else {
      children.add(const SizedBox(width: _kSnackBarPadding));
    }
218 219
    final CurvedAnimation heightAnimation = new CurvedAnimation(parent: animation, curve: _snackBarHeightCurve);
    final CurvedAnimation fadeAnimation = new CurvedAnimation(parent: animation, curve: _snackBarFadeCurve, reverseCurve: const Threshold(0.0));
220 221 222
    return new ClipRect(
      child: new AnimatedBuilder(
        animation: heightAnimation,
223
        builder: (BuildContext context, Widget child) {
224
          return new Align(
225
            alignment: FractionalOffsetDirectional.topStart,
226 227 228
            heightFactor: heightAnimation.value,
            child: child
          );
229
        },
Hixie's avatar
Hixie committed
230 231
        child: new Semantics(
          container: true,
232 233
          child: new Dismissible(
            key: const Key('dismissible'),
234
            direction: DismissDirection.down,
235
            resizeDuration: null,
236
            onDismissed: (DismissDirection direction) {
237
              Scaffold.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.swipe);
238 239
            },
            child: new Material(
240
              elevation: 6.0,
241
              color: backgroundColor ?? _kSnackBackground,
242
              child: new Theme(
243
                data: darkTheme,
244 245 246 247 248
                child: new FadeTransition(
                  opacity: fadeAnimation,
                  child: new Row(
                    children: children,
                    crossAxisAlignment: CrossAxisAlignment.center
Hixie's avatar
Hixie committed
249
                  )
250 251 252 253 254
                )
              )
            )
          )
        )
255 256
      )
    );
257
  }
258

Hixie's avatar
Hixie committed
259
  // API for Scaffold.addSnackBar():
260

261
  /// Creates an animation controller useful for driving a snack bar's entrance and exit animation.
262
  static AnimationController createAnimationController({ @required TickerProvider vsync }) {
263
    return new AnimationController(
264
      duration: _kSnackBarTransitionDuration,
265 266
      debugLabel: 'SnackBar',
      vsync: vsync,
Hixie's avatar
Hixie committed
267 268
    );
  }
269

270 271 272 273
  /// Creates a copy of this snack bar but with the animation replaced with the given animation.
  ///
  /// If the original snack bar lacks a key, the newly created snack bar will
  /// use the given fallback key.
274
  SnackBar withAnimation(Animation<double> newAnimation, { Key fallbackKey }) {
Hixie's avatar
Hixie committed
275
    return new SnackBar(
276
      key: key ?? fallbackKey,
Hixie's avatar
Hixie committed
277
      content: content,
278
      backgroundColor: backgroundColor,
279
      action: action,
Hixie's avatar
Hixie committed
280
      duration: duration,
281
      animation: newAnimation
Hixie's avatar
Hixie committed
282 283
    );
  }
284
}