button.dart 11.3 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 'colors.dart';
9
import 'constants.dart';
10
import 'debug.dart';
11
import 'flat_button.dart';
12 13
import 'ink_well.dart';
import 'material.dart';
14
import 'raised_button.dart';
15
import 'theme.dart';
16

17 18 19 20
/// Whether a button should use the accent color for its text.
///
/// See also:
///
21 22 23
///  * [ButtonTheme], which uses this enum to define the [ButtonTheme.textTheme].
///  * [RaisedButton], which styles itself based on the ambient [ButtonTheme].
///  * [FlatButton], which styles itself based on the ambient [ButtonTheme].
24
enum ButtonTextTheme {
25 26 27 28 29 30
  /// The button should use the normal color (e.g., black or white depending on the [ThemeData.brightness]) for its text.
  normal,

  /// The button should use the accent color (e.g., [ThemeData.accentColor]) for its text.
  accent,
}
31

32 33 34 35
/// Defines the button color used by a widget subtree.
///
/// See also:
///
36 37 38
///  * [ButtonTextTheme], which is used by [textTheme].
///  * [RaisedButton], which styles itself based on the ambient [ButtonTheme].
///  * [FlatButton], which styles itself based on the ambient [ButtonTheme].
39
class ButtonTheme extends InheritedWidget {
40 41 42 43
  /// Creates a button theme.
  ///
  /// The child argument is required.
  const ButtonTheme({
44
    Key key,
45 46 47 48
    this.textTheme: ButtonTextTheme.normal,
    this.minWidth: 88.0,
    this.height: 36.0,
    this.padding: const EdgeInsets.symmetric(horizontal: 16.0),
49
    Widget child
50 51
  }) : super(key: key, child: child);

52 53
  /// Creates a button theme that is appropriate for button bars, as used in
  /// dialog footers and in the headers of data tables.
54 55 56 57 58
  ///
  /// This theme is denser, with a smaller [minWidth] and [padding], than the
  /// default theme. Also, this theme uses [ButtonTextTheme.accent] rather than
  /// [ButtonTextTheme.normal].
  ///
59 60 61 62 63
  /// For best effect, the label of the button at the edge of the container
  /// should have text that ends up wider than 64.0 pixels. This ensures that
  /// the alignment of the text matches the alignment of the edge of the
  /// container.
  ///
64 65
  /// For example, buttons at the bottom of [Dialog] or [Card] widgets use this
  /// button theme.
66
  const ButtonTheme.bar({
67 68 69 70 71 72 73
    Key key,
    this.textTheme: ButtonTextTheme.accent,
    this.minWidth: 64.0,
    this.height: 36.0,
    this.padding: const EdgeInsets.symmetric(horizontal: 8.0),
    Widget child
  }) : super(key: key, child: child);
74

75
  /// The button color that this subtree should use.
76
  final ButtonTextTheme textTheme;
77

78 79 80 81 82 83
  /// The smallest horizontal extent that the button will occupy.
  ///
  /// Defaults to 88.0 logical pixels.
  final double minWidth;

  /// The vertical extent of the button.
84
  ///
85 86 87 88 89 90
  /// Defaults to 36.0 logical pixels.
  final double height;

  /// The amount of space to surround the child inside the bounds of the button.
  ///
  /// Defaults to 16.0 pixels of horizontal padding.
91
  final EdgeInsetsGeometry padding;
92

93
  /// The closest instance of this class that encloses the given context.
94 95 96 97 98 99
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// ButtonTheme theme = ButtonTheme.of(context);
  /// ```
100
  static ButtonTheme of(BuildContext context) {
101
    final ButtonTheme result = context.inheritFromWidgetOfExactType(ButtonTheme);
102
    return result ?? const ButtonTheme();
103 104
  }

105
  @override
106 107 108 109 110 111
  bool updateShouldNotify(ButtonTheme oldTheme) {
    return textTheme != oldTheme.textTheme
        || padding != oldTheme.padding
        || minWidth != oldTheme.minWidth
        || height != oldTheme.height;
  }
112 113
}

114
/// The framework for building material design buttons.
115
///
116 117 118
/// Rather than using this class directly, consider using [FlatButton] or
/// [RaisedButton], which configure this class with appropriate defaults that
/// match the material design specification.
119 120 121
///
/// MaterialButtons whose [onPressed] handler is null will be disabled. To have
/// an enabled button, make sure to pass a non-null value for onPressed.
122 123 124 125 126 127 128
///
/// If you want an ink-splash effect for taps, but don't want to use a button,
/// consider using [InkWell] directly.
///
/// See also:
///
///  * [IconButton], to create buttons that contain icons rather than text.
129 130 131 132 133
class MaterialButton extends StatefulWidget {
  /// Creates a material button.
  ///
  /// Rather than creating a material button directly, consider using
  /// [FlatButton] or [RaisedButton].
134
  const MaterialButton({
135
    Key key,
136
    this.colorBrightness,
137
    this.textTheme,
138
    this.textColor,
139
    this.color,
140 141
    this.highlightColor,
    this.splashColor,
142 143 144 145 146
    this.elevation,
    this.highlightElevation,
    this.minWidth,
    this.height,
    this.padding,
147
    @required this.onPressed,
148
    this.child
149
  }) : super(key: key);
150

151 152 153
  /// The theme brightness to use for this button.
  ///
  /// Defaults to the brightness from [ThemeData.brightness].
154
  final Brightness colorBrightness;
155 156 157 158

  /// The color scheme to use for this button's text.
  ///
  /// Defaults to the button color from [ButtonTheme].
159
  final ButtonTextTheme textTheme;
160

161
  /// The color to use for this button's text.
162
  final Color textColor;
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177
  /// The primary color of the button, as printed on the [Material], while it
  /// is in its default (unpressed, enabled) state.
  ///
  /// Defaults to null, meaning that the color is automatically derived from the [Theme].
  ///
  /// Typically, a material design color will be used, as follows:
  ///
  /// ```dart
  ///  new MaterialButton(
  ///    color: Colors.blue[500],
  ///    onPressed: _handleTap,
  ///    child: new Text('DEMO'),
  ///  ),
  /// ```
178 179
  final Color color;

180 181 182 183 184 185 186
  /// The primary color of the button when the button is in the down (pressed) state.
  /// The splash is represented as a circular overlay that appears above the
  /// [highlightColor] overlay. The splash overlay has a center point that matches
  /// the hit point of the user touch event. The splash overlay will expand to
  /// fill the button area if the touch is held for long enough time. If the splash
  /// color has transparency then the highlight and button color will show through.
  ///
187
  /// Defaults to the Theme's splash color, [ThemeData.splashColor].
188 189 190 191 192 193 194
  final Color splashColor;

  /// The secondary color of the button when the button is in the down (pressed)
  /// state. The higlight color is represented as a solid color that is overlaid over the
  /// button color (if any). If the highlight color has transparency, the button color
  /// will show through. The highlight fades in quickly as the button is held down.
  ///
195
  /// Defaults to the Theme's highlight color, [ThemeData.highlightColor].
196 197
  final Color highlightColor;

198 199
  /// The z-coordinate at which to place this button. This controls the size of
  /// the shadow below the button.
200
  ///
201
  /// Defaults to 0.
202 203 204 205 206 207 208
  ///
  /// See also:
  ///
  ///  * [FlatButton], a material button specialized for the case where the
  ///    elevation is zero.
  ///  * [RaisedButton], a material button specialized for the case where the
  ///    elevation is non-zero.
209
  final double elevation;
210

211 212
  /// The z-coordinate at which to place this button when highlighted. This
  /// controls the size of the shadow below the button.
213
  ///
214
  /// Defaults to 0.
215 216 217 218
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
219
  final double highlightElevation;
220 221 222 223 224 225 226 227 228 229 230 231 232 233

  /// The smallest horizontal extent that the button will occupy.
  ///
  /// Defaults to the value from the current [ButtonTheme].
  final double minWidth;

  /// The vertical extent of the button.
  ///
  /// Defaults to the value from the current [ButtonTheme].
  final double height;

  /// The amount of space to surround the child inside the bounds of the button.
  ///
  /// Defaults to the value from the current [ButtonTheme].
234
  final EdgeInsetsGeometry padding;
235

236
  /// The callback that is called when the button is tapped or otherwise activated.
237 238
  ///
  /// If this is set to null, the button will be disabled.
239
  final VoidCallback onPressed;
Hixie's avatar
Hixie committed
240

241 242 243
  /// The widget below this widget in the tree.
  final Widget child;

244 245
  /// Whether the button is enabled or disabled. Buttons are disabled by default. To
  /// enable a button, set its [onPressed] property to a non-null value.
246 247
  bool get enabled => onPressed != null;

248 249 250
  @override
  _MaterialButtonState createState() => new _MaterialButtonState();

251
  @override
252
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
253 254
    super.debugFillProperties(description);
    description.add(new FlagProperty('enabled', value: enabled, ifFalse: 'disabled'));
Hixie's avatar
Hixie committed
255
  }
256 257
}

258 259
class _MaterialButtonState extends State<MaterialButton> {
  bool _highlight = false;
260

261
  Brightness get _colorBrightness {
262
    return widget.colorBrightness ?? Theme.of(context).brightness;
263 264
  }

265
  Color get _textColor {
266 267 268 269
    if (widget.textColor != null)
      return widget.textColor;
    if (widget.enabled) {
      switch (widget.textTheme ?? ButtonTheme.of(context).textTheme) {
270
        case ButtonTextTheme.accent:
271
          return Theme.of(context).accentColor;
272 273
        case ButtonTextTheme.normal:
          switch (_colorBrightness) {
274
            case Brightness.light:
275
              return Colors.black87;
276
            case Brightness.dark:
277 278 279
              return Colors.white;
          }
      }
280
    } else {
281
      assert(_colorBrightness != null);
282
      switch (_colorBrightness) {
283
        case Brightness.light:
284
          return Colors.black26;
285
        case Brightness.dark:
286 287
          return Colors.white30;
      }
288
    }
pq's avatar
pq committed
289
    return null;
290 291
  }

292 293
  void _handleHighlightChanged(bool value) {
    setState(() {
294
      _highlight = value;
295 296 297
    });
  }

298
  @override
299
  Widget build(BuildContext context) {
300
    assert(debugCheckHasMaterial(context));
301
    final ThemeData theme = Theme.of(context);
302
    final Color textColor = _textColor;
303
    final TextStyle style = theme.textTheme.button.copyWith(color: textColor);
304
    final ButtonTheme buttonTheme = ButtonTheme.of(context);
305
    final double height = widget.height ?? buttonTheme.height;
306
    final double elevation = (_highlight ? widget.highlightElevation : widget.elevation) ?? 0.0;
307
    final bool hasColorOrElevation = (widget.color != null || elevation > 0);
308
    Widget contents = IconTheme.merge(
309 310 311 312
      data: new IconThemeData(
        color: textColor
      ),
      child: new InkWell(
313
        borderRadius: hasColorOrElevation ? null : kMaterialEdges[MaterialType.button],
314 315 316
        highlightColor: widget.highlightColor ?? theme.highlightColor,
        splashColor: widget.splashColor ?? theme.splashColor,
        onTap: widget.onPressed,
317 318
        onHighlightChanged: _handleHighlightChanged,
        child: new Container(
319
          padding: widget.padding ?? ButtonTheme.of(context).padding,
320 321
          child: new Center(
            widthFactor: 1.0,
322
            child: widget.child
323
          )
324
        )
325
      )
326
    );
327
    if (hasColorOrElevation) {
328 329
      contents = new Material(
        type: MaterialType.button,
330
        color: widget.color,
331 332 333 334 335
        elevation: elevation,
        textStyle: style,
        child: contents
      );
    } else {
336
      contents = new AnimatedDefaultTextStyle(
337
        style: style,
338
        duration: kThemeChangeDuration,
339 340 341
        child: contents
      );
    }
342 343
    return new ConstrainedBox(
      constraints: new BoxConstraints(
344
        minWidth: widget.minWidth ?? buttonTheme.minWidth,
345 346 347
        minHeight: height,
        maxHeight: height
      ),
348
      child: contents
349 350 351
    );
  }
}