outline_button.dart 20.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
6
import 'package:flutter/rendering.dart';
7 8 9 10
import 'package:flutter/widgets.dart';

import 'button_theme.dart';
import 'colors.dart';
11
import 'material_button.dart';
12
import 'material_state.dart';
13 14
import 'raised_button.dart';
import 'theme.dart';
15
import 'theme_data.dart';
16 17

// The total time to make the button's fill color opaque and change
18
// its elevation. Only applies when highlightElevation > 0.0.
19
const Duration _kPressDuration = Duration(milliseconds: 150);
20 21

// Half of _kPressDuration: just the time to change the button's
22
// elevation. Only applies when highlightElevation > 0.0.
23
const Duration _kElevationDuration = Duration(milliseconds: 75);
24

25
/// Similar to a [FlatButton] with a thin grey rounded rectangle border.
26
///
27 28 29 30 31 32 33 34 35 36 37
/// ### This class is obsolete, please use [OutlinedButton] instead.
///
/// FlatButton, RaisedButton, and OutlineButton have been replaced by
/// TextButton, ElevatedButton, and OutlinedButton respectively.
/// ButtonTheme has been replaced by TextButtonTheme,
/// ElevatedButtonTheme, and OutlinedButtonTheme. The original classes
/// will be deprecated soon, please migrate code that uses them.
/// There's a detailed migration guide for the new button and button
/// theme classes in
/// [flutter.dev/go/material-button-migration-guide](https://flutter.dev/go/material-button-migration-guide).
///
38 39 40 41 42
/// The outline button's border shape is defined by [shape]
/// and its appearance is defined by [borderSide], [disabledBorderColor],
/// and [highlightedBorderColor]. By default the border is a one pixel
/// wide grey rounded rectangle that does not change when the button is
/// pressed or disabled. By default the button's background is transparent.
43
///
44
/// If the [onPressed] or [onLongPress] callbacks are null, then the button will be disabled and by
45 46
/// default will resemble a flat button in the [disabledColor].
///
47 48 49 50 51 52 53
/// The button's [highlightElevation], which defines the size of the
/// drop shadow when the button is pressed, is 0.0 (no shadow) by default.
/// If [highlightElevation] is given a value greater than 0.0 then the button
/// becomes a cross between [RaisedButton] and [FlatButton]: a bordered
/// button whose elevation increases and whose background becomes opaque
/// when the button is pressed.
///
54 55 56
/// If you want an ink-splash effect for taps, but don't want to use a button,
/// consider using [InkWell] directly.
///
57
/// Outline buttons have a minimum size of 88.0 by 36.0 which can be overridden
58 59
/// with [ButtonTheme].
///
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
/// {@tool dartpad --template=stateless_widget_scaffold_center}
///
/// Here is an example of a basic [OutlineButton].
///
/// ```dart
///   Widget build(BuildContext context) {
///     return OutlineButton(
///       onPressed: () {
///         print('Received click');
///       },
///       child: Text('Click Me'),
///     );
///   }
/// ```
/// {@end-tool}
///
76 77 78 79 80 81 82 83
/// See also:
///
///  * [RaisedButton], a filled material design button with a shadow.
///  * [FlatButton], a material design button without a shadow.
///  * [DropdownButton], a button that shows options to select from.
///  * [FloatingActionButton], the round button in material applications.
///  * [IconButton], to create buttons that just contain icons.
///  * [InkWell], which implements the ink splash part of a flat button.
84
///  * <https://material.io/design/components/buttons.html>
85
class OutlineButton extends MaterialButton {
86
  /// Create an outline button.
87
  ///
88
  /// The [highlightElevation] argument must be null or a positive value
89
  /// and the [autofocus] and [clipBehavior] arguments must not be null.
90
  const OutlineButton({
91 92 93 94 95 96 97 98 99 100 101 102 103
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    MouseCursor? mouseCursor,
    ButtonTextTheme? textTheme,
    Color? textColor,
    Color? disabledTextColor,
    Color? color,
    Color? focusColor,
    Color? hoverColor,
    Color? highlightColor,
    Color? splashColor,
    double? highlightElevation,
104 105 106
    this.borderSide,
    this.disabledBorderColor,
    this.highlightedBorderColor,
107 108 109
    EdgeInsetsGeometry? padding,
    VisualDensity? visualDensity,
    ShapeBorder? shape,
110
    Clip clipBehavior = Clip.none,
111
    FocusNode? focusNode,
112
    bool autofocus = false,
113 114
    MaterialTapTargetSize? materialTapTargetSize,
    Widget? child,
115
  }) : assert(highlightElevation == null || highlightElevation >= 0.0),
116
       assert(clipBehavior != null),
117
       assert(autofocus != null),
118 119 120
       super(
         key: key,
         onPressed: onPressed,
121
         onLongPress: onLongPress,
122
         mouseCursor: mouseCursor,
123 124 125 126
         textTheme: textTheme,
         textColor: textColor,
         disabledTextColor: disabledTextColor,
         color: color,
127 128
         focusColor: focusColor,
         hoverColor: hoverColor,
129 130 131 132
         highlightColor: highlightColor,
         splashColor: splashColor,
         highlightElevation: highlightElevation,
         padding: padding,
133
         visualDensity: visualDensity,
134 135
         shape: shape,
         clipBehavior: clipBehavior,
136
         focusNode: focusNode,
137
         materialTapTargetSize: materialTapTargetSize,
138
         autofocus: autofocus,
139 140
         child: child,
       );
141 142 143 144 145 146 147

  /// Create an outline 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.
  ///
148
  /// The [highlightElevation] argument must be null or a positive value. The
149
  /// [icon], [label], [autofocus], and [clipBehavior] arguments must not be null.
150
  factory OutlineButton.icon({
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    MouseCursor? mouseCursor,
    ButtonTextTheme? textTheme,
    Color? textColor,
    Color? disabledTextColor,
    Color? color,
    Color? focusColor,
    Color? hoverColor,
    Color? highlightColor,
    Color? splashColor,
    double? highlightElevation,
    Color? highlightedBorderColor,
    Color? disabledBorderColor,
    BorderSide? borderSide,
    EdgeInsetsGeometry? padding,
    VisualDensity? visualDensity,
    ShapeBorder? shape,
170
    Clip clipBehavior,
171
    FocusNode? focusNode,
172
    bool autofocus,
173 174 175
    MaterialTapTargetSize? materialTapTargetSize,
    required Widget icon,
    required Widget label,
176
  }) = _OutlineButtonWithIcon;
177 178 179

  /// The outline border's color when the button is [enabled] and pressed.
  ///
180 181
  /// By default the border's color does not change when the button
  /// is pressed.
182
  ///
183
  /// This field is ignored if [BorderSide.color] is a [MaterialStateProperty<Color>].
184
  final Color? highlightedBorderColor;
185 186 187

  /// The outline border's color when the button is not [enabled].
  ///
188 189
  /// By default the outline border's color does not change when the
  /// button is disabled.
190
  ///
191
  /// This field is ignored if [BorderSide.color] is a [MaterialStateProperty<Color>].
192
  final Color? disabledBorderColor;
193

194 195
  /// Defines the color of the border when the button is enabled but not
  /// pressed, and the border outline's width and style in general.
196
  ///
197 198
  /// If the border side's [BorderSide.style] is [BorderStyle.none], then
  /// an outline is not drawn.
199
  ///
200
  /// If null the default border's style is [BorderStyle.solid], its
201
  /// [BorderSide.width] is 1.0, and its color is a light shade of grey.
202
  ///
203
  /// If [BorderSide.color] is a [MaterialStateProperty<Color>], [MaterialStateProperty.resolve]
204 205
  /// is used in all states and both [highlightedBorderColor] and [disabledBorderColor]
  /// are ignored.
206
  final BorderSide? borderSide;
207 208

  @override
209 210 211
  Widget build(BuildContext context) {
    final ButtonThemeData buttonTheme = ButtonTheme.of(context);
    return _OutlineButton(
212
      autofocus: autofocus,
213
      onPressed: onPressed,
214
      onLongPress: onLongPress,
215
      mouseCursor: mouseCursor,
216 217 218 219 220
      brightness: buttonTheme.getBrightness(this),
      textTheme: textTheme,
      textColor: buttonTheme.getTextColor(this),
      disabledTextColor: buttonTheme.getDisabledTextColor(this),
      color: color,
221 222
      focusColor: buttonTheme.getFocusColor(this),
      hoverColor: buttonTheme.getHoverColor(this),
223 224 225 226 227
      highlightColor: buttonTheme.getHighlightColor(this),
      splashColor: buttonTheme.getSplashColor(this),
      highlightElevation: buttonTheme.getHighlightElevation(this),
      borderSide: borderSide,
      disabledBorderColor: disabledBorderColor,
228
      highlightedBorderColor: highlightedBorderColor ?? buttonTheme.colorScheme!.primary,
229
      padding: buttonTheme.getPadding(this),
230
      visualDensity: visualDensity,
231 232
      shape: buttonTheme.getShape(this),
      clipBehavior: clipBehavior,
233
      focusNode: focusNode,
234
      materialTapTargetSize: materialTapTargetSize,
235 236 237
      child: child,
    );
  }
238 239

  @override
240 241
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
242
    properties.add(DiagnosticsProperty<BorderSide>('borderSide', borderSide, defaultValue: null));
243 244
    properties.add(ColorProperty('disabledBorderColor', disabledBorderColor, defaultValue: null));
    properties.add(ColorProperty('highlightedBorderColor', highlightedBorderColor, defaultValue: null));
245 246 247
  }
}

Shi-Hao Hong's avatar
Shi-Hao Hong committed
248
// The type of OutlineButtons created with OutlineButton.icon.
249
//
250 251
// This class only exists to give OutlineButtons created with OutlineButton.icon
// a distinct class for the sake of ButtonTheme. It can not be instantiated.
252
class _OutlineButtonWithIcon extends OutlineButton with MaterialButtonWithIconMixin {
253
  _OutlineButtonWithIcon({
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    MouseCursor? mouseCursor,
    ButtonTextTheme? textTheme,
    Color? textColor,
    Color? disabledTextColor,
    Color? color,
    Color? focusColor,
    Color? hoverColor,
    Color? highlightColor,
    Color? splashColor,
    double? highlightElevation,
    Color? highlightedBorderColor,
    Color? disabledBorderColor,
    BorderSide? borderSide,
    EdgeInsetsGeometry? padding,
    VisualDensity? visualDensity,
    ShapeBorder? shape,
273
    Clip clipBehavior = Clip.none,
274
    FocusNode? focusNode,
275
    bool autofocus = false,
276 277 278
    MaterialTapTargetSize? materialTapTargetSize,
    required Widget icon,
    required Widget label,
279
  }) : assert(highlightElevation == null || highlightElevation >= 0.0),
280
       assert(clipBehavior != null),
281
       assert(autofocus != null),
282 283 284 285 286
       assert(icon != null),
       assert(label != null),
       super(
         key: key,
         onPressed: onPressed,
287
         onLongPress: onLongPress,
288
         mouseCursor: mouseCursor,
289 290 291 292
         textTheme: textTheme,
         textColor: textColor,
         disabledTextColor: disabledTextColor,
         color: color,
293 294
         focusColor: focusColor,
         hoverColor: hoverColor,
295 296 297 298 299 300 301
         highlightColor: highlightColor,
         splashColor: splashColor,
         highlightElevation: highlightElevation,
         disabledBorderColor: disabledBorderColor,
         highlightedBorderColor: highlightedBorderColor,
         borderSide: borderSide,
         padding: padding,
302
         visualDensity: visualDensity,
303 304
         shape: shape,
         clipBehavior: clipBehavior,
305
         focusNode: focusNode,
306
         autofocus: autofocus,
307
         materialTapTargetSize: materialTapTargetSize,
308 309 310 311 312 313 314 315 316 317 318 319 320
         child: Row(
           mainAxisSize: MainAxisSize.min,
           children: <Widget>[
             icon,
             const SizedBox(width: 8.0),
             label,
           ],
         ),
       );
}

class _OutlineButton extends StatefulWidget {
  const _OutlineButton({
321 322
    Key? key,
    required this.onPressed,
323
    this.onLongPress,
324
    this.mouseCursor,
325
    required this.brightness,
326
    this.textTheme,
327 328
    required this.textColor,
    required this.disabledTextColor,
329
    this.color,
330 331 332 333 334
    required this.focusColor,
    required this.hoverColor,
    required this.highlightColor,
    required this.splashColor,
    required this.highlightElevation,
335 336
    this.borderSide,
    this.disabledBorderColor,
337 338
    required this.highlightedBorderColor,
    required this.padding,
339
    this.visualDensity,
340
    required this.shape,
341
    this.clipBehavior = Clip.none,
342
    this.focusNode,
343
    this.autofocus = false,
344
    this.child,
345
    this.materialTapTargetSize,
346 347
  }) : assert(highlightElevation != null && highlightElevation >= 0.0),
       assert(highlightedBorderColor != null),
348
       assert(clipBehavior != null),
349
       assert(autofocus != null),
350 351
       super(key: key);

352 353 354
  final VoidCallback? onPressed;
  final VoidCallback? onLongPress;
  final MouseCursor? mouseCursor;
355
  final Brightness brightness;
356
  final ButtonTextTheme? textTheme;
357 358
  final Color textColor;
  final Color disabledTextColor;
359
  final Color? color;
360
  final Color splashColor;
361 362
  final Color focusColor;
  final Color hoverColor;
363 364
  final Color highlightColor;
  final double highlightElevation;
365 366
  final BorderSide? borderSide;
  final Color? disabledBorderColor;
367 368
  final Color highlightedBorderColor;
  final EdgeInsetsGeometry padding;
369
  final VisualDensity? visualDensity;
370 371
  final ShapeBorder shape;
  final Clip clipBehavior;
372
  final FocusNode? focusNode;
373
  final bool autofocus;
374 375
  final Widget? child;
  final MaterialTapTargetSize? materialTapTargetSize;
376

377
  bool get enabled => onPressed != null || onLongPress != null;
378 379 380 381 382 383 384

  @override
  _OutlineButtonState createState() => _OutlineButtonState();
}


class _OutlineButtonState extends State<_OutlineButton> with SingleTickerProviderStateMixin {
385 386 387
  late AnimationController _controller;
  late Animation<double> _fillAnimation;
  late Animation<double> _elevationAnimation;
388 389 390 391 392 393
  bool _pressed = false;

  @override
  void initState() {
    super.initState();

394 395 396 397 398 399 400
    // When highlightElevation > 0.0, the Material widget animates its
    // shape (which includes the outline border) and elevation over
    // _kElevationDuration. When pressed, the button makes its fill
    // color opaque white first, and then sets its
    // highlightElevation. We can't change the elevation while the
    // button's fill is translucent, because the shadow fills the
    // interior of the button.
401

402
    _controller = AnimationController(
403
      duration: _kPressDuration,
404
      vsync: this,
405
    );
406
    _fillAnimation = CurvedAnimation(
407 408 409 410 411
      parent: _controller,
      curve: const Interval(0.0, 0.5,
        curve: Curves.fastOutSlowIn,
      ),
    );
412
    _elevationAnimation = CurvedAnimation(
413 414 415 416 417 418
      parent: _controller,
      curve: const Interval(0.5, 0.5),
      reverseCurve: const Interval(1.0, 1.0),
    );
  }

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
  @override
  void didUpdateWidget(_OutlineButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (_pressed && !widget.enabled) {
      _pressed = false;
      _controller.reverse();
    }
  }

  void _handleHighlightChanged(bool value) {
    if (_pressed == value)
      return;
    setState(() {
      _pressed = value;
      if (value)
        _controller.forward();
      else
        _controller.reverse();
    });
  }

440 441 442 443 444 445
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

446
  Color _getFillColor() {
447 448
    if (widget.highlightElevation == null || widget.highlightElevation == 0.0)
      return Colors.transparent;
449
    final Color color = widget.color ?? Theme.of(context).canvasColor;
450
    final Tween<Color?> colorTween = ColorTween(
451 452 453
      begin: color.withAlpha(0x00),
      end: color.withAlpha(0xFF),
    );
454
    return colorTween.evaluate(_fillAnimation)!;
455 456
  }

457
  Color? get _outlineColor {
458 459
    // If outline color is a `MaterialStateProperty`, it will be used in all
    // states, otherwise we determine the outline color in the current state.
460 461
    if (widget.borderSide?.color is MaterialStateProperty<Color?>)
      return widget.borderSide!.color;
462 463 464 465 466 467 468
    if (!widget.enabled)
      return widget.disabledBorderColor;
    if (_pressed)
      return widget.highlightedBorderColor;
    return widget.borderSide?.color;
  }

469
  BorderSide _getOutline() {
470
    if (widget.borderSide?.style == BorderStyle.none)
471
      return widget.borderSide!;
472

473
    final Color themeColor = Theme.of(context).colorScheme.onSurface.withOpacity(0.12);
474

475
    return BorderSide(
476
      color: _outlineColor ?? themeColor,
477
      width: widget.borderSide?.width ?? 1.0,
478 479 480 481
    );
  }

  double _getHighlightElevation() {
482 483
    if (widget.highlightElevation == null || widget.highlightElevation == 0.0)
      return 0.0;
484
    return Tween<double>(
485
      begin: 0.0,
486
      end: widget.highlightElevation,
487 488 489 490 491
    ).evaluate(_elevationAnimation);
  }

  @override
  Widget build(BuildContext context) {
492
    final ThemeData theme = Theme.of(context);
493

494
    return AnimatedBuilder(
495
      animation: _controller,
496
      builder: (BuildContext context, Widget? child) {
497
        return RaisedButton(
498
          autofocus: widget.autofocus,
499
          textColor: widget.textColor,
500
          disabledTextColor: widget.disabledTextColor,
501 502
          color: _getFillColor(),
          splashColor: widget.splashColor,
503 504
          focusColor: widget.focusColor,
          hoverColor: widget.hoverColor,
505 506 507
          highlightColor: widget.highlightColor,
          disabledColor: Colors.transparent,
          onPressed: widget.onPressed,
508
          onLongPress: widget.onLongPress,
509
          mouseCursor: widget.mouseCursor,
510 511
          elevation: 0.0,
          disabledElevation: 0.0,
512 513
          focusElevation: 0.0,
          hoverElevation: 0.0,
514
          highlightElevation: _getHighlightElevation(),
515
          onHighlightChanged: _handleHighlightChanged,
516
          padding: widget.padding,
517
          visualDensity: widget.visualDensity ?? theme.visualDensity,
518
          shape: _OutlineBorder(
519 520
            shape: widget.shape,
            side: _getOutline(),
521
          ),
522
          clipBehavior: widget.clipBehavior,
523
          focusNode: widget.focusNode,
524
          animationDuration: _kElevationDuration,
525
          materialTapTargetSize: widget.materialTapTargetSize,
526 527 528 529 530 531 532 533 534
          child: widget.child,
        );
      },
    );
  }
}

// Render the button's outline border using using the OutlineButton's
// border parameters and the button or buttonTheme's shape.
535
class _OutlineBorder extends ShapeBorder implements MaterialStateProperty<ShapeBorder>{
536
  const _OutlineBorder({
537 538
    required this.shape,
    required this.side,
539 540 541 542 543 544 545 546
  }) : assert(shape != null),
       assert(side != null);

  final ShapeBorder shape;
  final BorderSide side;

  @override
  EdgeInsetsGeometry get dimensions {
547
    return EdgeInsets.all(side.width);
548 549 550 551
  }

  @override
  ShapeBorder scale(double t) {
552
    return _OutlineBorder(
553 554 555 556 557 558
      shape: shape.scale(t),
      side: side.scale(t),
    );
  }

  @override
559
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
560 561
    assert(t != null);
    if (a is _OutlineBorder) {
562
      return _OutlineBorder(
563
        side: BorderSide.lerp(a.side, side, t),
564
        shape: ShapeBorder.lerp(a.shape, shape, t)!,
565 566 567 568 569 570
      );
    }
    return super.lerpFrom(a, t);
  }

  @override
571
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
572 573
    assert(t != null);
    if (b is _OutlineBorder) {
574
      return _OutlineBorder(
575
        side: BorderSide.lerp(side, b.side, t),
576
        shape: ShapeBorder.lerp(shape, b.shape, t)!,
577 578 579 580 581 582
      );
    }
    return super.lerpTo(b, t);
  }

  @override
583
  Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
584 585 586 587
    return shape.getInnerPath(rect.deflate(side.width), textDirection: textDirection);
  }

  @override
588
  Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
589 590 591 592
    return shape.getOuterPath(rect, textDirection: textDirection);
  }

  @override
593
  void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) {
594 595 596 597
    switch (side.style) {
      case BorderStyle.none:
        break;
      case BorderStyle.solid:
598
        canvas.drawPath(shape.getOuterPath(rect, textDirection: textDirection), side.toPaint());
599 600 601 602
    }
  }

  @override
603
  bool operator ==(Object other) {
604 605
    if (identical(this, other))
      return true;
606
    if (other.runtimeType != runtimeType)
607
      return false;
608 609 610
    return other is _OutlineBorder
        && other.side == side
        && other.shape == shape;
611 612 613 614
  }

  @override
  int get hashCode => hashValues(side, shape);
615 616 617 618 619 620 621 622

  @override
  ShapeBorder resolve(Set<MaterialState> states) {
    return _OutlineBorder(
      shape: shape,
      side: side.copyWith(color: MaterialStateProperty.resolveAs<Color>(side.color, states),
    ));
  }
623
}