text_button.dart 16.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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 'colors.dart';
import 'constants.dart';
16 17
import 'ink_ripple.dart';
import 'ink_well.dart';
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import 'material_state.dart';
import 'text_button_theme.dart';
import 'theme.dart';
import 'theme_data.dart';

/// A Material Design "Text Button".
///
/// Use text buttons on toolbars, in dialogs, or inline with other
/// content but offset from that content with padding so that the
/// button's presence is obvious. Text buttons do not have visible
/// borders and must therefore rely on their position relative to
/// other content for context. In dialogs and cards, they should be
/// grouped together in one of the bottom corners. Avoid using text
/// buttons where they would blend in with other content, for example
/// in the middle of lists.
///
/// A text button is a label [child] displayed on a (zero elevation)
/// [Material] widget. The label's [Text] and [Icon] widgets are
/// displayed in the [style]'s [ButtonStyle.foregroundColor]. The
/// button reacts to touches by filling with the [style]'s
/// [ButtonStyle.backgroundColor].
///
/// The text button's default style is defined by [defaultStyleOf].
/// The style of this text button can be overridden with its [style]
/// parameter. The style of all text buttons in a subtree can be
/// overridden with the [TextButtonTheme] and the style of all of the
/// text buttons in an app can be overridden with the [Theme]'s
/// [ThemeData.textButtonTheme] property.
///
/// The static [styleFrom] method is a convenient way to create a
/// text button [ButtonStyle] from simple values.
///
/// If the [onPressed] and [onLongPress] callbacks are null, then this
/// button will be disabled, it will not react to touch.
///
53 54 55 56 57 58 59 60 61 62 63 64 65
/// {@tool dartpad --template=stateless_widget_scaffold}
///
/// This sample shows how to render a disabled TextButton, an enabled TextButton
/// and lastly a TextButton with gradient background.
///
/// ```dart
/// Widget build(BuildContext context) {
///   return Center(
///     child: Column(
///       mainAxisSize: MainAxisSize.min,
///       children: <Widget>[
///         TextButton(
///            style: TextButton.styleFrom(
66
///              textStyle: const TextStyle(fontSize: 20),
67 68 69 70 71 72 73
///            ),
///            onPressed: null,
///            child: const Text('Disabled'),
///         ),
///         const SizedBox(height: 30),
///         TextButton(
///           style: TextButton.styleFrom(
74
///             textStyle: const TextStyle(fontSize: 20),
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
///           ),
///           onPressed: () {},
///           child: const Text('Enabled'),
///         ),
///         const SizedBox(height: 30),
///         ClipRRect(
///           borderRadius: BorderRadius.circular(4),
///           child: Stack(
///             children: <Widget>[
///               Positioned.fill(
///                 child: Container(
///                   decoration: const BoxDecoration(
///                     gradient: LinearGradient(
///                       colors: <Color>[
///                         Color(0xFF0D47A1),
///                         Color(0xFF1976D2),
///                         Color(0xFF42A5F5),
///                       ],
///                     ),
///                   ),
///                 ),
///               ),
///               TextButton(
///                 style: TextButton.styleFrom(
///                   padding: const EdgeInsets.all(16.0),
///                   primary: Colors.white,
101
///                   textStyle: const TextStyle(fontSize: 20),
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
///                 ),
///                 onPressed: () {},
///                  child: const Text('Gradient'),
///               ),
///             ],
///           ),
///         ),
///       ],
///     ),
///   );
/// }
///
/// ```
/// {@end-tool}
///
117 118 119
/// See also:
///
///  * [OutlinedButton], a [TextButton] with a border outline.
120
///  * [ElevatedButton], a filled button whose material elevates when pressed.
121 122 123 124 125 126
///  * <https://material.io/design/components/buttons.html>
class TextButton extends ButtonStyleButton {
  /// Create a TextButton.
  ///
  /// The [autofocus] and [clipBehavior] arguments must not be null.
  const TextButton({
127 128 129 130 131
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
132 133
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
134
    required Widget child,
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  }) : super(
    key: key,
    onPressed: onPressed,
    onLongPress: onLongPress,
    style: style,
    focusNode: focusNode,
    autofocus: autofocus,
    clipBehavior: clipBehavior,
    child: child,
  );

  /// Create a text button from a pair of widgets that serve as the button's
  /// [icon] and [label].
  ///
  /// The icon and label are arranged in a row and padded by 8 logical pixels
  /// at the ends, with an 8 pixel gap in between.
  ///
  /// The [icon] and [label] arguments must not be null.
  factory TextButton.icon({
154 155 156 157 158 159 160
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
161 162
    required Widget icon,
    required Widget label,
163 164 165 166 167 168
  }) = _TextButtonWithIcon;

  /// A static convenience method that constructs a text button
  /// [ButtonStyle] given simple values.
  ///
  /// The [primary], and [onSurface] colors are used to to create a
169 170 171 172 173 174
  /// [MaterialStateProperty] [ButtonStyle.foregroundColor] value in the same
  /// way that [defaultStyleOf] uses the [ColorScheme] colors with the same
  /// names. Specify a value for [primary] to specify the color of the button's
  /// text and icons as well as the overlay colors used to indicate the hover,
  /// focus, and pressed states. Use [onSurface] to specify the button's
  /// disabled text and icon color.
175 176
  ///
  /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
177
  /// parameters are used to construct [ButtonStyle.mouseCursor].
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  ///
  /// 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
  /// [TextButton], as well as its overlay color, with all of the
  /// standard opacity adjustments for the pressed, focused, and
  /// hovered states, one could write:
  ///
  /// ```dart
  /// TextButton(
  ///   style: TextButton.styleFrom(primary: Colors.green),
  /// )
  /// ```
  static ButtonStyle styleFrom({
197 198 199 200 201 202 203 204
    Color? primary,
    Color? onSurface,
    Color? backgroundColor,
    Color? shadowColor,
    double? elevation,
    TextStyle? textStyle,
    EdgeInsetsGeometry? padding,
    Size? minimumSize,
205
    Size? fixedSize,
206
    Size? maximumSize,
207 208 209 210 211 212 213 214
    BorderSide? side,
    OutlinedBorder? shape,
    MouseCursor? enabledMouseCursor,
    MouseCursor? disabledMouseCursor,
    VisualDensity? visualDensity,
    MaterialTapTargetSize? tapTargetSize,
    Duration? animationDuration,
    bool? enableFeedback,
215
    AlignmentGeometry? alignment,
216
    InteractiveInkFeatureFactory? splashFactory,
217
  }) {
218
    final MaterialStateProperty<Color?>? foregroundColor = (onSurface == null && primary == null)
219 220
      ? null
      : _TextButtonDefaultForeground(primary, onSurface);
221
    final MaterialStateProperty<Color?>? overlayColor = (primary == null)
222 223
      ? null
      : _TextButtonDefaultOverlay(primary);
224
    final MaterialStateProperty<MouseCursor>? mouseCursor = (enabledMouseCursor == null && disabledMouseCursor == null)
225
      ? null
226
      : _TextButtonDefaultMouseCursor(enabledMouseCursor!, disabledMouseCursor!);
227 228 229 230 231 232 233 234 235 236

    return ButtonStyle(
      textStyle: ButtonStyleButton.allOrNull<TextStyle>(textStyle),
      backgroundColor: ButtonStyleButton.allOrNull<Color>(backgroundColor),
      foregroundColor: foregroundColor,
      overlayColor: overlayColor,
      shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor),
      elevation: ButtonStyleButton.allOrNull<double>(elevation),
      padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding),
      minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize),
237
      fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize),
238
      maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize),
239 240 241 242 243 244 245
      side: ButtonStyleButton.allOrNull<BorderSide>(side),
      shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape),
      mouseCursor: mouseCursor,
      visualDensity: visualDensity,
      tapTargetSize: tapTargetSize,
      animationDuration: animationDuration,
      enableFeedback: enableFeedback,
246
      alignment: alignment,
247
      splashFactory: splashFactory,
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    );
  }

  /// 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 and is transparent by default.
  ///
  /// 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
  /// properties that are not followed by by a sublist have the same
  /// 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.
  ///
274 275
  /// The color of the [ButtonStyle.textStyle] is not used, the
  /// [ButtonStyle.foregroundColor] color is used instead.
276 277 278 279 280 281 282 283 284
  ///
  /// * `textStyle` - Theme.textTheme.button
  /// * `backgroundColor` - transparent
  /// * `foregroundColor`
  ///   * disabled - Theme.colorScheme.onSurface(0.38)
  ///   * others - Theme.colorScheme.primary
  /// * `overlayColor`
  ///   * hovered - Theme.colorScheme.primary(0.04)
  ///   * focused or pressed - Theme.colorScheme.primary(0.12)
285
  /// * `shadowColor` - Theme.shadowColor
286 287 288 289 290 291 292
  /// * `elevation` - 0
  /// * `padding`
  ///   * `textScaleFactor <= 1` - all(8)
  ///   * `1 < textScaleFactor <= 2` - lerp(all(8), horizontal(8))
  ///   * `2 < textScaleFactor <= 3` - lerp(horizontal(8), horizontal(4))
  ///   * `3 < textScaleFactor` - horizontal(4)
  /// * `minimumSize` - Size(64, 36)
293
  /// * `fixedSize` - null
294
  /// * `maximumSize` - Size.infinite
295
  /// * `side` - null
296 297 298 299 300 301 302 303
  /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
  /// * `mouseCursor`
  ///   * disabled - SystemMouseCursors.forbidden
  ///   * others - SystemMouseCursors.click
  /// * `visualDensity` - theme.visualDensity
  /// * `tapTargetSize` - theme.materialTapTargetSize
  /// * `animationDuration` - kThemeChangeDuration
  /// * `enableFeedback` - true
304
  /// * `alignment` - Alignment.center
305
  /// * `splashFactory` - InkRipple.splashFactory
306 307 308 309 310 311 312
  ///
  /// The default padding values for the [TextButton.icon] factory are slightly different:
  ///
  /// * `padding`
  ///   * `textScaleFactor <= 1` - all(8)
  ///   * `1 < textScaleFactor <= 2 `- lerp(all(8), horizontal(4))
  ///   * `2 < textScaleFactor` - horizontal(4)
313 314 315 316 317
  ///
  /// 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.
318 319
  @override
  ButtonStyle defaultStyleOf(BuildContext context) {
320
    final ThemeData theme = Theme.of(context);
321 322 323 324 325 326
    final ColorScheme colorScheme = theme.colorScheme;

    final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
      const EdgeInsets.all(8),
      const EdgeInsets.symmetric(horizontal: 8),
      const EdgeInsets.symmetric(horizontal: 4),
327
      MediaQuery.maybeOf(context)?.textScaleFactor ?? 1,
328 329 330 331 332 333
    );

    return styleFrom(
      primary: colorScheme.primary,
      onSurface: colorScheme.onSurface,
      backgroundColor: Colors.transparent,
334
      shadowColor: theme.shadowColor,
335 336 337 338
      elevation: 0,
      textStyle: theme.textTheme.button,
      padding: scaledPadding,
      minimumSize: const Size(64, 36),
339
      maximumSize: Size.infinite,
340
      side: null,
341 342 343 344 345 346 347
      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,
348
      alignment: Alignment.center,
349
      splashFactory: InkRipple.splashFactory,
350 351 352 353 354 355
    );
  }

  /// Returns the [TextButtonThemeData.style] of the closest
  /// [TextButtonTheme] ancestor.
  @override
356 357
  ButtonStyle? themeStyleOf(BuildContext context) {
    return TextButtonTheme.of(context).style;
358 359 360 361
  }
}

@immutable
362
class _TextButtonDefaultForeground extends MaterialStateProperty<Color?> {
363 364
  _TextButtonDefaultForeground(this.primary, this.onSurface);

365 366
  final Color? primary;
  final Color? onSurface;
367 368

  @override
369
  Color? resolve(Set<MaterialState> states) {
370 371 372 373 374 375 376 377 378 379 380 381
    if (states.contains(MaterialState.disabled))
      return onSurface?.withOpacity(0.38);
    return primary;
  }

  @override
  String toString() {
    return '{disabled: ${onSurface?.withOpacity(0.38)}, otherwise: $primary}';
  }
}

@immutable
382
class _TextButtonDefaultOverlay extends MaterialStateProperty<Color?> {
383 384 385 386 387
  _TextButtonDefaultOverlay(this.primary);

  final Color primary;

  @override
388
  Color? resolve(Set<MaterialState> states) {
389
    if (states.contains(MaterialState.hovered))
390
      return primary.withOpacity(0.04);
391
    if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed))
392
      return primary.withOpacity(0.12);
393 394 395 396 397
    return null;
  }

  @override
  String toString() {
398
    return '{hovered: ${primary.withOpacity(0.04)}, focused,pressed: ${primary.withOpacity(0.12)}, otherwise: null}';
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
  }
}

@immutable
class _TextButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor> with Diagnosticable {
  _TextButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor);

  final MouseCursor enabledCursor;
  final MouseCursor disabledCursor;

  @override
  MouseCursor resolve(Set<MaterialState> states) {
    if (states.contains(MaterialState.disabled))
      return disabledCursor;
    return enabledCursor;
  }
}

class _TextButtonWithIcon extends TextButton {
  _TextButtonWithIcon({
419 420 421 422 423 424 425 426 427
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
    required Widget icon,
    required Widget label,
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  }) : 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: _TextButtonWithIconChild(icon: icon, label: label),
      );

  @override
  ButtonStyle defaultStyleOf(BuildContext context) {
    final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
      const EdgeInsets.all(8),
      const EdgeInsets.symmetric(horizontal: 4),
      const EdgeInsets.symmetric(horizontal: 4),
447
      MediaQuery.maybeOf(context)?.textScaleFactor ?? 1,
448 449
    );
    return super.defaultStyleOf(context).copyWith(
450
      padding: MaterialStateProperty.all<EdgeInsetsGeometry>(scaledPadding),
451 452 453 454 455
    );
  }
}

class _TextButtonWithIconChild extends StatelessWidget {
456 457 458 459 460
  const _TextButtonWithIconChild({
    Key? key,
    required this.label,
    required this.icon,
  }) : super(key: key);
461 462 463 464 465 466

  final Widget label;
  final Widget icon;

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