elevated_button.dart 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;
import 'dart:ui' show lerpDouble;

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

import 'button_style.dart';
import 'button_style_button.dart';
import 'color_scheme.dart';
import 'constants.dart';
15
import 'elevated_button_theme.dart';
16 17
import 'ink_ripple.dart';
import 'ink_well.dart';
18 19 20 21
import 'material_state.dart';
import 'theme.dart';
import 'theme_data.dart';

22
/// A Material Design "elevated button".
23
///
24
/// Use elevated buttons to add dimension to otherwise mostly flat
25
/// layouts, e.g.  in long busy lists of content, or in wide
26
/// spaces. Avoid using elevated buttons on already-elevated content
27 28
/// such as dialogs or cards.
///
29
/// An elevated button is a label [child] displayed on a [Material]
30 31
/// widget whose [Material.elevation] increases when the button is
/// pressed. The label's [Text] and [Icon] widgets are displayed in
32
/// [style]'s [ButtonStyle.foregroundColor] and the button's filled
33 34
/// background is the [ButtonStyle.backgroundColor].
///
35 36
/// The elevated button's default style is defined by
/// [defaultStyleOf].  The style of this elevated button can be
37
/// overridden with its [style] parameter. The style of all elevated
38
/// buttons in a subtree can be overridden with the
39
/// [ElevatedButtonTheme], and the style of all of the elevated
40
/// buttons in an app can be overridden with the [Theme]'s
41
/// [ThemeData.elevatedButtonTheme] property.
42 43
///
/// The static [styleFrom] method is a convenient way to create a
44
/// elevated button [ButtonStyle] from simple values.
45 46 47 48
///
/// If [onPressed] and [onLongPress] callbacks are null, then the
/// button will be disabled.
///
49 50 51 52 53
/// {@tool dartpad --template=stateful_widget_scaffold}
///
/// This sample produces an enabled and a disabled ElevatedButton.
///
/// ```dart
54
/// @override
55 56
/// Widget build(BuildContext context) {
///   final ButtonStyle style =
57
///     ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
///
///   return Center(
///     child: Column(
///       mainAxisSize: MainAxisSize.min,
///       children: <Widget>[
///         ElevatedButton(
///            style: style,
///            onPressed: null,
///            child: const Text('Disabled'),
///         ),
///         const SizedBox(height: 30),
///         ElevatedButton(
///           style: style,
///           onPressed: () {},
///           child: const Text('Enabled'),
///         ),
///       ],
///     ),
///   );
/// }
///
/// ```
/// {@end-tool}
///
82 83 84 85 86
/// See also:
///
///  * [TextButton], a simple flat button without a shadow.
///  * [OutlinedButton], a [TextButton] with a border outline.
///  * <https://material.io/design/components/buttons.html>
87 88
class ElevatedButton extends ButtonStyleButton {
  /// Create an ElevatedButton.
89 90
  ///
  /// The [autofocus] and [clipBehavior] arguments must not be null.
91
  const ElevatedButton({
92 93 94 95 96
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
97 98
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
99
    required Widget? child,
100 101 102 103 104 105 106 107 108 109 110
  }) : super(
    key: key,
    onPressed: onPressed,
    onLongPress: onLongPress,
    style: style,
    focusNode: focusNode,
    autofocus: autofocus,
    clipBehavior: clipBehavior,
    child: child,
  );

111
  /// Create an elevated button from a pair of widgets that serve as the button's
112 113 114 115 116 117
  /// [icon] and [label].
  ///
  /// The icon and label are arranged in a row and padded by 12 logical pixels
  /// at the start, and 16 at the end, with an 8 pixel gap in between.
  ///
  /// The [icon] and [label] arguments must not be null.
118
  factory ElevatedButton.icon({
119 120 121 122 123 124 125
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
126 127
    required Widget icon,
    required Widget label,
128
  }) = _ElevatedButtonWithIcon;
129

130
  /// A static convenience method that constructs an elevated button
131 132
  /// [ButtonStyle] given simple values.
  ///
Jan Mewes's avatar
Jan Mewes committed
133
  /// The [onPrimary], and [onSurface] colors are used to create a
134 135
  /// [MaterialStateProperty] [ButtonStyle.foregroundColor] value in the same
  /// way that [defaultStyleOf] uses the [ColorScheme] colors with the same
136
  /// names. Specify a value for [onPrimary] to specify the color of the
137 138 139 140
  /// button's text and icons as well as the overlay colors used to indicate the
  /// hover, focus, and pressed states. Use [primary] for the button's background
  /// fill color and [onSurface] to specify the button's disabled text, icon,
  /// and fill color.
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  ///
  /// The button's elevations are defined relative to the [elevation]
  /// parameter. The disabled elevation is the same as the parameter
  /// value, [elevation] + 2 is used when the button is hovered
  /// or focused, and elevation + 6 is used when the button is pressed.
  ///
  /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
  /// parameters are used to construct [ButtonStyle].mouseCursor.
  ///
  /// All of the other parameters are either used directly or used to
  /// create a [MaterialStateProperty] with a single value for all
  /// states.
  ///
  /// All parameters default to null, by default this method returns
  /// a [ButtonStyle] that doesn't override anything.
  ///
  /// For example, to override the default text and icon colors for a
158
  /// [ElevatedButton], as well as its overlay color, with all of the
159 160 161 162
  /// standard opacity adjustments for the pressed, focused, and
  /// hovered states, one could write:
  ///
  /// ```dart
163
  /// ElevatedButton(
164
  ///   style: ElevatedButton.styleFrom(primary: Colors.green),
165 166 167
  /// )
  /// ```
  static ButtonStyle styleFrom({
168 169 170 171 172 173 174 175
    Color? primary,
    Color? onPrimary,
    Color? onSurface,
    Color? shadowColor,
    double? elevation,
    TextStyle? textStyle,
    EdgeInsetsGeometry? padding,
    Size? minimumSize,
176
    Size? fixedSize,
177
    Size? maximumSize,
178 179 180 181 182 183 184 185
    BorderSide? side,
    OutlinedBorder? shape,
    MouseCursor? enabledMouseCursor,
    MouseCursor? disabledMouseCursor,
    VisualDensity? visualDensity,
    MaterialTapTargetSize? tapTargetSize,
    Duration? animationDuration,
    bool? enableFeedback,
186
    AlignmentGeometry? alignment,
187
    InteractiveInkFeatureFactory? splashFactory,
188
  }) {
189
    final MaterialStateProperty<Color?>? backgroundColor = (onSurface == null && primary == null)
190
      ? null
191
      : _ElevatedButtonDefaultBackground(primary, onSurface);
192
    final MaterialStateProperty<Color?>? foregroundColor = (onSurface == null && onPrimary == null)
193
      ? null
194
      : _ElevatedButtonDefaultForeground(onPrimary, onSurface);
195
    final MaterialStateProperty<Color?>? overlayColor = (onPrimary == null)
196
      ? null
197
      : _ElevatedButtonDefaultOverlay(onPrimary);
198
    final MaterialStateProperty<double>? elevationValue = (elevation == null)
199
      ? null
200
      : _ElevatedButtonDefaultElevation(elevation);
201
    final MaterialStateProperty<MouseCursor?>? mouseCursor = (enabledMouseCursor == null && disabledMouseCursor == null)
202
      ? null
203
      : _ElevatedButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor);
204 205

    return ButtonStyle(
206
      textStyle: MaterialStateProperty.all<TextStyle?>(textStyle),
207 208 209 210 211 212 213
      backgroundColor: backgroundColor,
      foregroundColor: foregroundColor,
      overlayColor: overlayColor,
      shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor),
      elevation: elevationValue,
      padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding),
      minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize),
214
      fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize),
215
      maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize),
216 217 218 219 220 221 222
      side: ButtonStyleButton.allOrNull<BorderSide>(side),
      shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape),
      mouseCursor: mouseCursor,
      visualDensity: visualDensity,
      tapTargetSize: tapTargetSize,
      animationDuration: animationDuration,
      enableFeedback: enableFeedback,
223
      alignment: alignment,
224
      splashFactory: splashFactory,
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    );
  }

  /// Defines the button's default appearance.
  ///
  /// The button [child]'s [Text] and [Icon] widgets are rendered with
  /// the [ButtonStyle]'s foreground color. The button's [InkWell] adds
  /// the style's overlay color when the button is focused, hovered
  /// or pressed. The button's background color becomes its [Material]
  /// color.
  ///
  /// All of the ButtonStyle's defaults appear below. In this list
  /// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color
  /// scheme values like "onSurface(0.38)" are shorthand for
  /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued
nt4f04uNd's avatar
nt4f04uNd committed
240
  /// properties that are not followed by a sublist have the same
241 242 243 244 245 246 247 248
  /// value for all states, otherwise the values are as specified for
  /// each state, and "others" means all other states.
  ///
  /// The `textScaleFactor` is the value of
  /// `MediaQuery.of(context).textScaleFactor` and the names of the
  /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been
  /// abbreviated for readability.
  ///
249 250
  /// The color of the [ButtonStyle.textStyle] is not used, the
  /// [ButtonStyle.foregroundColor] color is used instead.
251 252 253 254 255 256 257 258 259 260 261
  ///
  /// * `textStyle` - Theme.textTheme.button
  /// * `backgroundColor`
  ///   * disabled - Theme.colorScheme.onSurface(0.12)
  ///   * others - Theme.colorScheme.primary
  /// * `foregroundColor`
  ///   * disabled - Theme.colorScheme.onSurface(0.38)
  ///   * others - Theme.colorScheme.onPrimary
  /// * `overlayColor`
  ///   * hovered - Theme.colorScheme.onPrimary(0.08)
  ///   * focused or pressed - Theme.colorScheme.onPrimary(0.24)
262
  /// * `shadowColor` - Theme.shadowColor
263 264
  /// * `elevation`
  ///   * disabled - 0
265 266 267
  ///   * default - 2
  ///   * hovered or focused - 4
  ///   * pressed - 8
268 269 270 271 272 273
  /// * `padding`
  ///   * textScaleFactor <= 1 - horizontal(16)
  ///   * `1 < textScaleFactor <= 2` - lerp(horizontal(16), horizontal(8))
  ///   * `2 < textScaleFactor <= 3` - lerp(horizontal(8), horizontal(4))
  ///   * `3 < textScaleFactor` - horizontal(4)
  /// * `minimumSize` - Size(64, 36)
274
  /// * `fixedSize` - null
275
  /// * `maximumSize` - Size.infinite
276
  /// * `side` - null
277 278 279 280 281 282 283 284
  /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
  /// * `mouseCursor`
  ///   * disabled - SystemMouseCursors.forbidden
  ///   * others - SystemMouseCursors.click
  /// * `visualDensity` - theme.visualDensity
  /// * `tapTargetSize` - theme.materialTapTargetSize
  /// * `animationDuration` - kThemeChangeDuration
  /// * `enableFeedback` - true
285
  /// * `alignment` - Alignment.center
286
  /// * `splashFactory` - InkRipple.splashFactory
287
  ///
288
  /// The default padding values for the [ElevatedButton.icon] factory are slightly different:
289 290 291 292 293 294
  ///
  /// * `padding`
  ///   * `textScaleFactor <= 1` - start(12) end(16)
  ///   * `1 < textScaleFactor <= 2` - lerp(start(12) end(16), horizontal(8))
  ///   * `2 < textScaleFactor <= 3` - lerp(horizontal(8), horizontal(4))
  ///   * `3 < textScaleFactor` - horizontal(4)
295 296 297 298 299
  ///
  /// The default value for `side`, which defines the appearance of the button's
  /// outline, is null. That means that the outline is defined by the button
  /// shape's [OutlinedBorder.side]. Typically the default value of an
  /// [OutlinedBorder]'s side is [BorderSide.none], so an outline is not drawn.
300 301
  @override
  ButtonStyle defaultStyleOf(BuildContext context) {
302
    final ThemeData theme = Theme.of(context);
303 304 305 306 307 308
    final ColorScheme colorScheme = theme.colorScheme;

    final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
      const EdgeInsets.symmetric(horizontal: 16),
      const EdgeInsets.symmetric(horizontal: 8),
      const EdgeInsets.symmetric(horizontal: 4),
309
      MediaQuery.maybeOf(context)?.textScaleFactor ?? 1,
310 311 312 313 314 315
    );

    return styleFrom(
      primary: colorScheme.primary,
      onPrimary: colorScheme.onPrimary,
      onSurface: colorScheme.onSurface,
316
      shadowColor: theme.shadowColor,
317 318 319 320
      elevation: 2,
      textStyle: theme.textTheme.button,
      padding: scaledPadding,
      minimumSize: const Size(64, 36),
321
      maximumSize: Size.infinite,
322
      side: null,
323 324 325 326 327 328 329
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
      enabledMouseCursor: SystemMouseCursors.click,
      disabledMouseCursor: SystemMouseCursors.forbidden,
      visualDensity: theme.visualDensity,
      tapTargetSize: theme.materialTapTargetSize,
      animationDuration: kThemeChangeDuration,
      enableFeedback: true,
330
      alignment: Alignment.center,
331
      splashFactory: InkRipple.splashFactory,
332 333 334
    );
  }

335 336
  /// Returns the [ElevatedButtonThemeData.style] of the closest
  /// [ElevatedButtonTheme] ancestor.
337
  @override
338 339
  ButtonStyle? themeStyleOf(BuildContext context) {
    return ElevatedButtonTheme.of(context).style;
340 341 342 343
  }
}

@immutable
344
class _ElevatedButtonDefaultBackground extends MaterialStateProperty<Color?> with Diagnosticable {
345
  _ElevatedButtonDefaultBackground(this.primary, this.onSurface);
346

347 348
  final Color? primary;
  final Color? onSurface;
349 350

  @override
351
  Color? resolve(Set<MaterialState> states) {
352 353 354 355 356 357 358
    if (states.contains(MaterialState.disabled))
      return onSurface?.withOpacity(0.12);
    return primary;
  }
}

@immutable
359
class _ElevatedButtonDefaultForeground extends MaterialStateProperty<Color?> with Diagnosticable {
360
  _ElevatedButtonDefaultForeground(this.onPrimary, this.onSurface);
361

362 363
  final Color? onPrimary;
  final Color? onSurface;
364 365

  @override
366
  Color? resolve(Set<MaterialState> states) {
367 368 369 370 371 372 373
    if (states.contains(MaterialState.disabled))
      return onSurface?.withOpacity(0.38);
    return onPrimary;
  }
}

@immutable
374
class _ElevatedButtonDefaultOverlay extends MaterialStateProperty<Color?> with Diagnosticable {
375
  _ElevatedButtonDefaultOverlay(this.onPrimary);
376 377 378 379

  final Color onPrimary;

  @override
380
  Color? resolve(Set<MaterialState> states) {
381
    if (states.contains(MaterialState.hovered))
382
      return onPrimary.withOpacity(0.08);
383
    if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed))
384
      return onPrimary.withOpacity(0.24);
385 386 387 388 389
    return null;
  }
}

@immutable
390 391
class _ElevatedButtonDefaultElevation extends MaterialStateProperty<double> with Diagnosticable {
  _ElevatedButtonDefaultElevation(this.elevation);
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

  final double elevation;

  @override
  double resolve(Set<MaterialState> states) {
    if (states.contains(MaterialState.disabled))
      return 0;
    if (states.contains(MaterialState.hovered))
      return elevation + 2;
    if (states.contains(MaterialState.focused))
      return elevation + 2;
    if (states.contains(MaterialState.pressed))
      return elevation + 6;
    return elevation;
  }
}

@immutable
410
class _ElevatedButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor?> with Diagnosticable {
411
  _ElevatedButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor);
412

413 414
  final MouseCursor? enabledCursor;
  final MouseCursor? disabledCursor;
415 416

  @override
417
  MouseCursor? resolve(Set<MaterialState> states) {
418 419 420 421 422 423
    if (states.contains(MaterialState.disabled))
      return disabledCursor;
    return enabledCursor;
  }
}

424 425
class _ElevatedButtonWithIcon extends ElevatedButton {
  _ElevatedButtonWithIcon({
426 427 428 429 430 431 432 433 434
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
    required Widget icon,
    required Widget label,
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  }) : assert(icon != null),
       assert(label != null),
       super(
         key: key,
         onPressed: onPressed,
         onLongPress: onLongPress,
         style: style,
         focusNode: focusNode,
         autofocus: autofocus ?? false,
         clipBehavior: clipBehavior ?? Clip.none,
         child: _ElevatedButtonWithIconChild(icon: icon, label: label),
      );

  @override
  ButtonStyle defaultStyleOf(BuildContext context) {
    final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
      const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0),
      const EdgeInsets.symmetric(horizontal: 8),
      const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0),
454
      MediaQuery.maybeOf(context)?.textScaleFactor ?? 1,
455 456
    );
    return super.defaultStyleOf(context).copyWith(
457
      padding: MaterialStateProperty.all<EdgeInsetsGeometry>(scaledPadding),
458 459 460 461 462
    );
  }
}

class _ElevatedButtonWithIconChild extends StatelessWidget {
463
  const _ElevatedButtonWithIconChild({ Key? key, required this.label, required this.icon }) : super(key: key);
464 465 466 467 468 469

  final Widget label;
  final Widget icon;

  @override
  Widget build(BuildContext context) {
470
    final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1;
471
    final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;
472 473
    return Row(
      mainAxisSize: MainAxisSize.min,
474
      children: <Widget>[icon, SizedBox(width: gap), Flexible(child: label)],
475 476 477
    );
  }
}