outlined_button.dart 13.8 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
import 'material_state.dart';
import 'outlined_button_theme.dart';
import 'theme.dart';
import 'theme_data.dart';

/// A Material Design "Outlined Button"; essentially a [TextButton]
/// with an outlined border.
///
/// Outlined buttons are medium-emphasis buttons. They contain actions
/// that are important, but they aren’t the primary action in an app.
///
/// An outlined 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] and the outline's weight and color
/// are defined by [ButtonStyle.side].  The button reacts to touches
/// by filling with the [style]'s [ButtonStyle.backgroundColor].
///
/// The outlined button's default style is defined by [defaultStyleOf].
/// The style of this outline button can be overridden with its [style]
/// parameter. The style of all text buttons in a subtree can be
/// overridden with the [OutlinedButtonTheme] and the style of all of the
/// outlined buttons in an app can be overridden with the [Theme]'s
/// [ThemeData.outlinedButtonTheme] property.
///
43 44 45 46 47 48 49 50
/// Unlike [TextButton] or [ElevatedButton], outline buttons have a
/// default [ButtonStyle.side] which defines the appearance of the
/// outline.  Because the default `side` is non-null, it
/// unconditionally overrides the shape's [OutlinedBorder.side]. In
/// other words, to specify an outlined button's shape _and_ the
/// appearance of its outline, both the [ButtonStyle.shape] and
/// [ButtonStyle.side] properties must be specified.
///
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/// {@tool dartpad --template=stateless_widget_scaffold_center}
///
/// Here is an example of a basic [OutlinedButton].
///
/// ```dart
/// Widget build(BuildContext context) {
///   return OutlinedButton(
///     onPressed: () {
///       print('Received click');
///     },
///     child: const Text('Click Me'),
///   );
/// }
/// ```
/// {@end-tool}
///
67 68 69 70 71
/// The static [styleFrom] method is a convenient way to create a
/// outlined button [ButtonStyle] from simple values.
///
/// See also:
///
72
///  * [ElevatedButton], a filled material design button with a shadow.
73 74 75 76 77 78 79
///  * [TextButton], a material design button without a shadow.
///  * <https://material.io/design/components/buttons.html>
class OutlinedButton extends ButtonStyleButton {
  /// Create an OutlinedButton.
  ///
  /// The [autofocus] and [clipBehavior] arguments must not be null.
  const OutlinedButton({
80 81 82 83 84
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
85 86
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
87
    required Widget child,
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }) : 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 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.
  factory OutlinedButton.icon({
107 108 109 110 111 112 113
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
114 115
    required Widget icon,
    required Widget label,
116 117 118 119 120
  }) = _OutlinedButtonWithIcon;

  /// A static convenience method that constructs an outlined button
  /// [ButtonStyle] given simple values.
  ///
Jan Mewes's avatar
Jan Mewes committed
121
  /// The [primary], and [onSurface] colors are used to create a
122 123 124 125 126 127
  /// [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.
128 129
  ///
  /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
130
  /// parameters are used to construct [ButtonStyle.mouseCursor].
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  ///
  /// 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 shape and outline for an
  /// [OutlinedButton], one could write:
  ///
  /// ```dart
  /// OutlinedButton(
  ///   style: OutlinedButton.styleFrom(
  ///      shape: StadiumBorder(),
  ///      side: BorderSide(width: 2, color: Colors.green),
  ///   ),
  /// )
  /// ```
  static ButtonStyle styleFrom({
151 152 153 154 155 156 157 158
    Color? primary,
    Color? onSurface,
    Color? backgroundColor,
    Color? shadowColor,
    double? elevation,
    TextStyle? textStyle,
    EdgeInsetsGeometry? padding,
    Size? minimumSize,
159
    Size? fixedSize,
160
    Size? maximumSize,
161 162 163 164 165 166 167 168
    BorderSide? side,
    OutlinedBorder? shape,
    MouseCursor? enabledMouseCursor,
    MouseCursor? disabledMouseCursor,
    VisualDensity? visualDensity,
    MaterialTapTargetSize? tapTargetSize,
    Duration? animationDuration,
    bool? enableFeedback,
169
    AlignmentGeometry? alignment,
170
    InteractiveInkFeatureFactory? splashFactory,
171
  }) {
172
    final MaterialStateProperty<Color?>? foregroundColor = (onSurface == null && primary == null)
173 174
      ? null
      : _OutlinedButtonDefaultForeground(primary, onSurface);
175
    final MaterialStateProperty<Color?>? overlayColor = (primary == null)
176 177
      ? null
      : _OutlinedButtonDefaultOverlay(primary);
178
    final MaterialStateProperty<MouseCursor>? mouseCursor = (enabledMouseCursor == null && disabledMouseCursor == null)
179
      ? null
180
      : _OutlinedButtonDefaultMouseCursor(enabledMouseCursor!, disabledMouseCursor!);
181 182 183 184 185 186 187 188 189 190

    return ButtonStyle(
      textStyle: ButtonStyleButton.allOrNull<TextStyle>(textStyle),
      foregroundColor: foregroundColor,
      backgroundColor: ButtonStyleButton.allOrNull<Color>(backgroundColor),
      overlayColor: overlayColor,
      shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor),
      elevation: ButtonStyleButton.allOrNull<double>(elevation),
      padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding),
      minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize),
191
      fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize),
192
      maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize),
193 194 195 196 197 198 199
      side: ButtonStyleButton.allOrNull<BorderSide>(side),
      shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape),
      mouseCursor: mouseCursor,
      visualDensity: visualDensity,
      tapTargetSize: tapTargetSize,
      animationDuration: animationDuration,
      enableFeedback: enableFeedback,
200
      alignment: alignment,
201
      splashFactory: splashFactory,
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    );
  }

  /// Defines the button's default appearance.
  ///
  /// With the exception of [ButtonStyle.side], which defines the
  /// outline, and [ButtonStyle.padding], the returned style is the
  /// same as for [TextButton].
  ///
  /// 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
nt4f04uNd's avatar
nt4f04uNd committed
221
  /// properties that are not followed by a sublist have the same
222 223 224
  /// value for all states, otherwise the values are as specified for
  /// each state and "others" means all other states.
  ///
225
  /// The color of the [ButtonStyle.textStyle] is not used, the
226
  /// [ButtonStyle.foregroundColor] is used instead.
227 228 229 230 231 232 233 234 235
  ///
  /// * `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)
236
  /// * `shadowColor` - Theme.shadowColor
237 238 239 240 241 242 243
  /// * `elevation` - 0
  /// * `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)
244
  /// * `fixedSize` - null
245
  /// * `maximumSize` - Size.infinite
246 247 248 249 250 251 252 253 254
  /// * `side` - BorderSide(width: 1, color: Theme.colorScheme.onSurface(0.12))
  /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
  /// * `mouseCursor`
  ///   * disabled - SystemMouseCursors.forbidden
  ///   * others - SystemMouseCursors.click
  /// * `visualDensity` - theme.visualDensity
  /// * `tapTargetSize` - theme.materialTapTargetSize
  /// * `animationDuration` - kThemeChangeDuration
  /// * `enableFeedback` - true
255
  /// * `alignment` - Alignment.center
256
  /// * `splashFactory` - InkRipple.splashFactory
257 258
  @override
  ButtonStyle defaultStyleOf(BuildContext context) {
259
    final ThemeData theme = Theme.of(context);
260 261 262 263 264 265
    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),
266
      MediaQuery.maybeOf(context)?.textScaleFactor ?? 1,
267 268 269 270 271 272
    );

    return styleFrom(
      primary: colorScheme.primary,
      onSurface: colorScheme.onSurface,
      backgroundColor: Colors.transparent,
273
      shadowColor: theme.shadowColor,
274 275 276 277
      elevation: 0,
      textStyle: theme.textTheme.button,
      padding: scaledPadding,
      minimumSize: const Size(64, 36),
278
      maximumSize: Size.infinite,
279
      side: BorderSide(
280
        color: Theme.of(context).colorScheme.onSurface.withOpacity(0.12),
281 282
        width: 1,
      ),
283
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
284 285 286 287 288 289
      enabledMouseCursor: SystemMouseCursors.click,
      disabledMouseCursor: SystemMouseCursors.forbidden,
      visualDensity: theme.visualDensity,
      tapTargetSize: theme.materialTapTargetSize,
      animationDuration: kThemeChangeDuration,
      enableFeedback: true,
290
      alignment: Alignment.center,
291
      splashFactory: InkRipple.splashFactory,
292 293 294 295
    );
  }

  @override
296 297
  ButtonStyle? themeStyleOf(BuildContext context) {
    return OutlinedButtonTheme.of(context).style;
298 299 300 301
  }
}

@immutable
302
class _OutlinedButtonDefaultForeground extends MaterialStateProperty<Color?>  with Diagnosticable {
303 304
  _OutlinedButtonDefaultForeground(this.primary, this.onSurface);

305 306
  final Color? primary;
  final Color? onSurface;
307 308

  @override
309
  Color? resolve(Set<MaterialState> states) {
310 311 312 313 314 315 316
    if (states.contains(MaterialState.disabled))
      return onSurface?.withOpacity(0.38);
    return primary;
  }
}

@immutable
317
class _OutlinedButtonDefaultOverlay extends MaterialStateProperty<Color?> with Diagnosticable {
318 319 320 321 322
  _OutlinedButtonDefaultOverlay(this.primary);

  final Color primary;

  @override
323
  Color? resolve(Set<MaterialState> states) {
324
    if (states.contains(MaterialState.hovered))
325
      return primary.withOpacity(0.04);
326
    if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed))
327
      return primary.withOpacity(0.12);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    return null;
  }
}

@immutable
class _OutlinedButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor> with Diagnosticable {
  _OutlinedButtonDefaultMouseCursor(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 _OutlinedButtonWithIcon extends OutlinedButton {
  _OutlinedButtonWithIcon({
349 350 351 352 353 354 355 356 357
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
    required Widget icon,
    required Widget label,
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  }) : 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: _OutlinedButtonWithIconChild(icon: icon, label: label),
      );
}

class _OutlinedButtonWithIconChild extends StatelessWidget {
373 374 375 376 377
  const _OutlinedButtonWithIconChild({
    Key? key,
    required this.label,
    required this.icon,
  }) : super(key: key);
378 379 380 381 382 383

  final Widget label;
  final Widget icon;

  @override
  Widget build(BuildContext context) {
384
    final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1;
385
    final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;
386 387
    return Row(
      mainAxisSize: MainAxisSize.min,
388
      children: <Widget>[icon, SizedBox(width: gap), Flexible(child: label)],
389 390 391
    );
  }
}