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

5 6
// @dart = 2.8

7 8
import 'dart:math' as math;

9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/painting.dart';
11
import 'package:flutter/rendering.dart';
12
import 'package:flutter/widgets.dart';
13

14
import 'button.dart';
15
import 'colors.dart';
16
import 'floating_action_button_theme.dart';
17
import 'scaffold.dart';
18
import 'theme.dart';
19
import 'theme_data.dart';
Adam Barth's avatar
Adam Barth committed
20
import 'tooltip.dart';
21

22
const BoxConstraints _kSizeConstraints = BoxConstraints.tightFor(
23 24 25 26
  width: 56.0,
  height: 56.0,
);

27
const BoxConstraints _kMiniSizeConstraints = BoxConstraints.tightFor(
28 29 30 31
  width: 40.0,
  height: 40.0,
);

32
const BoxConstraints _kExtendedSizeConstraints = BoxConstraints(
33 34 35
  minHeight: 48.0,
  maxHeight: 48.0,
);
36 37 38 39 40 41

class _DefaultHeroTag {
  const _DefaultHeroTag();
  @override
  String toString() => '<default FloatingActionButton tag>';
}
42

43
/// A material design floating action button.
44 45
///
/// A floating action button is a circular icon button that hovers over content
46 47
/// to promote a primary action in the application. Floating action buttons are
/// most commonly used in the [Scaffold.floatingActionButton] field.
48
///
49 50
/// {@youtube 560 315 https://www.youtube.com/watch?v=2uaoEDOgk_I}
///
51 52
/// Use at most a single floating action button per screen. Floating action
/// buttons should be used for positive actions such as "create", "share", or
53 54 55
/// "navigate". (If more than one floating action button is used within a
/// [Route], then make sure that each button has a unique [heroTag], otherwise
/// an exception will be thrown.)
56
///
57
/// If the [onPressed] callback is null, then the button will be disabled and
58 59 60 61
/// will not react to touch. It is highly discouraged to disable a floating
/// action button as there is no indication to the user that the button is
/// disabled. Consider changing the [backgroundColor] if disabling the floating
/// action button.
62
///
63
/// {@tool dartpad --template=stateless_widget_material}
64
/// This example shows how to display a [FloatingActionButton] in a
65 66
/// [Scaffold], with a pink [backgroundColor] and a thumbs up [Icon].
///
67
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/floating_action_button.png)
68
///
69 70 71 72
/// ```dart
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
73
///       title: const Text('Floating Action Button'),
74 75
///     ),
///     body: Center(
76
///       child: const Text('Press the button below!')
77 78 79 80 81
///     ),
///     floatingActionButton: FloatingActionButton(
///       onPressed: () {
///         // Add your onPressed code here!
///       },
82 83
///       child: Icon(Icons.navigation),
///       backgroundColor: Colors.green,
84 85 86 87 88 89
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
90
/// {@tool dartpad --template=stateless_widget_material}
91
/// This example shows how to make an extended [FloatingActionButton] in a
92
/// [Scaffold], with a  pink [backgroundColor], a thumbs up [Icon] and a
93
/// [Text] label that reads "Approve".
94
///
95
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/floating_action_button_label.png)
96
///
97 98 99 100
/// ```dart
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
101
///       title: const Text('Floating Action Button Label'),
102 103
///     ),
///     body: Center(
104
///       child: const Text('Press the button with a label below!'),
105 106 107 108 109 110 111 112 113 114 115 116 117 118
///     ),
///     floatingActionButton: FloatingActionButton.extended(
///       onPressed: () {
///         // Add your onPressed code here!
///       },
///       label: Text('Approve'),
///       icon: Icon(Icons.thumb_up),
///       backgroundColor: Colors.pink,
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
119 120
/// See also:
///
121 122 123 124
///  * [Scaffold], in which floating action buttons typically live.
///  * [RaisedButton], another kind of button that appears to float above the
///    content.
///  * <https://material.io/design/components/buttons-floating-action-button.html>
125
class FloatingActionButton extends StatelessWidget {
126
  /// Creates a circular floating action button.
127
  ///
128
  /// The [mini] and [clipBehavior] arguments must not be null. Additionally,
129 130
  /// [elevation], [highlightElevation], and [disabledElevation] (if specified)
  /// must be non-negative.
131
  const FloatingActionButton({
132
    Key key,
133
    this.child,
Adam Barth's avatar
Adam Barth committed
134
    this.tooltip,
135
    this.foregroundColor,
136
    this.backgroundColor,
137 138
    this.focusColor,
    this.hoverColor,
139
    this.splashColor,
140
    this.heroTag = const _DefaultHeroTag(),
141
    this.elevation,
142 143
    this.focusElevation,
    this.hoverElevation,
144 145
    this.highlightElevation,
    this.disabledElevation,
146
    @required this.onPressed,
147
    this.mouseCursor,
148
    this.mini = false,
149
    this.shape,
150
    this.clipBehavior = Clip.none,
151
    this.focusNode,
152
    this.autofocus = false,
153
    this.materialTapTargetSize,
154
    this.isExtended = false,
155
  }) : assert(elevation == null || elevation >= 0.0),
156 157
       assert(focusElevation == null || focusElevation >= 0.0),
       assert(hoverElevation == null || hoverElevation >= 0.0),
158
       assert(highlightElevation == null || highlightElevation >= 0.0),
159 160
       assert(disabledElevation == null || disabledElevation >= 0.0),
       assert(mini != null),
161
       assert(clipBehavior != null),
162
       assert(isExtended != null),
163
       assert(autofocus != null),
164 165
       _sizeConstraints = mini ? _kMiniSizeConstraints : _kSizeConstraints,
       super(key: key);
166

167 168
  /// Creates a wider [StadiumBorder]-shaped floating action button with
  /// an optional [icon] and a [label].
169
  ///
170
  /// The [label], [autofocus], and [clipBehavior] arguments must not be null.
171 172
  /// Additionally, [elevation], [highlightElevation], and [disabledElevation]
  /// (if specified) must be non-negative.
173 174 175 176 177
  FloatingActionButton.extended({
    Key key,
    this.tooltip,
    this.foregroundColor,
    this.backgroundColor,
178 179
    this.focusColor,
    this.hoverColor,
180
    this.heroTag = const _DefaultHeroTag(),
181
    this.elevation,
182 183
    this.focusElevation,
    this.hoverElevation,
184
    this.splashColor,
185 186
    this.highlightElevation,
    this.disabledElevation,
187
    @required this.onPressed,
188
    this.mouseCursor = SystemMouseCursors.click,
189
    this.shape,
190
    this.isExtended = true,
191
    this.materialTapTargetSize,
192
    this.clipBehavior = Clip.none,
193
    this.focusNode,
194
    this.autofocus = false,
195
    Widget icon,
196
    @required Widget label,
197
  }) : assert(elevation == null || elevation >= 0.0),
198 199
       assert(focusElevation == null || focusElevation >= 0.0),
       assert(hoverElevation == null || hoverElevation >= 0.0),
200
       assert(highlightElevation == null || highlightElevation >= 0.0),
201 202
       assert(disabledElevation == null || disabledElevation >= 0.0),
       assert(isExtended != null),
203
       assert(clipBehavior != null),
204
       assert(autofocus != null),
205 206 207 208 209
       _sizeConstraints = _kExtendedSizeConstraints,
       mini = false,
       child = _ChildOverflowBox(
         child: Row(
           mainAxisSize: MainAxisSize.min,
210 211 212 213 214 215 216 217 218 219 220 221 222
           children: icon == null
             ? <Widget>[
                 const SizedBox(width: 20.0),
                 label,
                 const SizedBox(width: 20.0),
               ]
             : <Widget>[
                 const SizedBox(width: 16.0),
                 icon,
                 const SizedBox(width: 8.0),
                 label,
                 const SizedBox(width: 20.0),
               ],
223 224 225
         ),
       ),
       super(key: key);
226

227
  /// The widget below this widget in the tree.
228 229
  ///
  /// Typically an [Icon].
230
  final Widget child;
231

232 233 234 235
  /// Text that describes the action that will occur when the button is pressed.
  ///
  /// This text is displayed when the user long-presses on the button and is
  /// used for accessibility.
Adam Barth's avatar
Adam Barth committed
236
  final String tooltip;
237

238
  /// The default foreground color for icons and text within the button.
239
  ///
240 241 242 243 244 245 246 247 248
  /// If this property is null, then the [Theme]'s
  /// [ThemeData.floatingActionButtonTheme.foregroundColor] is used. If that
  /// property is also null, then the [Theme]'s
  /// [ThemeData.colorScheme.onSecondary] color is used.
  ///
  /// Although the color of theme's `accentIconTheme` currently provides a
  /// default that supercedes the `onSecondary` color, this dependency
  /// has been deprecated:  https://flutter.dev/go/remove-fab-accent-theme-dependency.
  /// It will be removed in the future.
249 250
  final Color foregroundColor;

251
  /// The button's background color.
252
  ///
253 254 255 256
  /// If this property is null, then the [Theme]'s
  /// [ThemeData.floatingActionButtonTheme.backgroundColor] is used. If that
  /// property is also null, then the [Theme]'s
  /// [ThemeData.colorScheme.secondary] color is used.
257
  final Color backgroundColor;
258

259 260 261 262 263 264 265 266 267 268 269
  /// The color to use for filling the button when the button has input focus.
  ///
  /// Defaults to [ThemeData.focusColor] for the current theme.
  final Color focusColor;

  /// The color to use for filling the button when the button has a pointer
  /// hovering over it.
  ///
  /// Defaults to [ThemeData.hoverColor] for the current theme.
  final Color hoverColor;

270 271 272 273 274 275
  /// The splash color for this [FloatingActionButton]'s [InkWell].
  ///
  /// If null, [FloatingActionButtonThemeData.splashColor] is used, if that is
  /// null, [ThemeData.splashColor] is used.
  final Color splashColor;

276 277 278
  /// The tag to apply to the button's [Hero] widget.
  ///
  /// Defaults to a tag that matches other floating action buttons.
279 280 281 282 283 284 285 286 287
  ///
  /// Set this to null explicitly if you don't want the floating action button to
  /// have a hero tag.
  ///
  /// If this is not explicitly set, then there can only be one
  /// [FloatingActionButton] per route (that is, per screen), since otherwise
  /// there would be a tag conflict (multiple heroes on one route can't have the
  /// same tag). The material design specification recommends only using one
  /// floating action button per screen.
288 289
  final Object heroTag;

290
  /// The callback that is called when the button is tapped or otherwise activated.
291 292
  ///
  /// If this is set to null, the button will be disabled.
293
  final VoidCallback onPressed;
294

295 296 297
  /// {@macro flutter.material.button.mouseCursor}
  final MouseCursor mouseCursor;

298
  /// The z-coordinate at which to place this button relative to its parent.
299
  ///
300 301 302 303
  /// This controls the size of the shadow below the floating action button.
  ///
  /// Defaults to 6, the appropriate elevation for floating action buttons. The
  /// value is always non-negative.
304 305 306 307 308
  ///
  /// See also:
  ///
  ///  * [highlightElevation], the elevation when the button is pressed.
  ///  * [disabledElevation], the elevation when the button is disabled.
309
  final double elevation;
310

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
  /// The z-coordinate at which to place this button relative to its parent when
  /// the button has the input focus.
  ///
  /// This controls the size of the shadow below the floating action button.
  ///
  /// Defaults to 8, the appropriate elevation for floating action buttons
  /// while they have focus. The value is always non-negative.
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
  ///  * [highlightElevation], the elevation when the button is pressed.
  ///  * [disabledElevation], the elevation when the button is disabled.
  final double focusElevation;

  /// The z-coordinate at which to place this button relative to its parent when
  /// the button is enabled and has a pointer hovering over it.
  ///
  /// This controls the size of the shadow below the floating action button.
  ///
  /// Defaults to 8, the appropriate elevation for floating action buttons while
  /// they have a pointer hovering over them. The value is always non-negative.
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
  ///  * [highlightElevation], the elevation when the button is pressed.
  ///  * [disabledElevation], the elevation when the button is disabled.
  final double hoverElevation;

341 342 343 344
  /// The z-coordinate at which to place this button relative to its parent when
  /// the user is touching the button.
  ///
  /// This controls the size of the shadow below the floating action button.
345 346
  ///
  /// Defaults to 12, the appropriate elevation for floating action buttons
347
  /// while they are being touched. The value is always non-negative.
348 349 350 351
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
352
  final double highlightElevation;
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  /// The z-coordinate at which to place this button when the button is disabled
  /// ([onPressed] is null).
  ///
  /// This controls the size of the shadow below the floating action button.
  ///
  /// Defaults to the same value as [elevation]. Setting this to zero makes the
  /// floating action button work similar to a [RaisedButton] but the titular
  /// "floating" effect is lost. The value is always non-negative.
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
  ///  * [highlightElevation], the elevation when the button is pressed.
  final double disabledElevation;

369 370 371 372
  /// Controls the size of this button.
  ///
  /// By default, floating action buttons are non-mini and have a height and
  /// width of 56.0 logical pixels. Mini floating action buttons have a height
373
  /// and width of 40.0 logical pixels with a layout width and height of 48.0
374 375 376
  /// logical pixels. (The extra 4 pixels of padding on each side are added as a
  /// result of the floating action button having [MaterialTapTargetSize.padded]
  /// set on the underlying [RawMaterialButton.materialTapTargetSize].)
Devon Carew's avatar
Devon Carew committed
377
  final bool mini;
378

379 380 381 382 383 384 385
  /// The shape of the button's [Material].
  ///
  /// The button's highlight and splash are clipped to this shape. If the
  /// button has an elevation, then its drop shadow is defined by this
  /// shape as well.
  final ShapeBorder shape;

386
  /// {@macro flutter.widgets.Clip}
387 388
  ///
  /// Defaults to [Clip.none], and must not be null.
389 390
  final Clip clipBehavior;

391 392 393 394 395 396 397 398 399 400 401
  /// True if this is an "extended" floating action button.
  ///
  /// Typically [extended] buttons have a [StadiumBorder] [shape]
  /// and have been created with the [FloatingActionButton.extended]
  /// constructor.
  ///
  /// The [Scaffold] animates the appearance of ordinary floating
  /// action buttons with scale and rotation transitions. Extended
  /// floating action buttons are scaled and faded in.
  final bool isExtended;

402
  /// {@macro flutter.widgets.Focus.focusNode}
403 404
  final FocusNode focusNode;

405 406 407
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

408 409 410 411 412 413
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [ThemeData.materialTapTargetSize].
  ///
  /// See also:
  ///
414
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
415 416
  final MaterialTapTargetSize materialTapTargetSize;

417 418
  final BoxConstraints _sizeConstraints;

419
  static const double _defaultElevation = 6;
420 421 422 423
  // TODO(gspencer): verify focus and hover elevation values are correct
  // according to spec.
  static const double _defaultFocusElevation = 8;
  static const double _defaultHoverElevation = 10;
424 425 426 427
  static const double _defaultHighlightElevation = 12;
  static const ShapeBorder _defaultShape = CircleBorder();
  static const ShapeBorder _defaultExtendedShape = StadiumBorder();

428
  @override
429
  Widget build(BuildContext context) {
430
    final ThemeData theme = Theme.of(context);
431 432
    final FloatingActionButtonThemeData floatingActionButtonTheme = theme.floatingActionButtonTheme;

433 434 435 436 437 438 439 440 441 442 443 444 445
    // Applications should no longer use accentIconTheme's color to configure
    // the foreground color of floating action buttons. For more information, see
    // https://flutter.dev/go/remove-fab-accent-theme-dependency.
    if (this.foregroundColor == null && floatingActionButtonTheme.foregroundColor == null) {
      final bool accentIsDark = theme.accentColorBrightness == Brightness.dark;
      final Color defaultAccentIconThemeColor = accentIsDark ? Colors.white : Colors.black;
      if (theme.accentIconTheme.color != defaultAccentIconThemeColor) {
        debugPrint(
          'Warning: '
          'The support for configuring the foreground color of '
          'FloatingActionButtons using ThemeData.accentIconTheme '
          'has been deprecated. Please use ThemeData.floatingActionButtonTheme '
          'instead. See '
446
          'https://flutter.dev/go/remove-fab-accent-theme-dependency. '
447 448 449 450 451
          'This feature was deprecated after v1.13.2.'
        );
      }
    }

452 453 454
    final Color foregroundColor = this.foregroundColor
      ?? floatingActionButtonTheme.foregroundColor
      ?? theme.colorScheme.onSecondary;
455 456 457 458 459 460 461 462 463
    final Color backgroundColor = this.backgroundColor
      ?? floatingActionButtonTheme.backgroundColor
      ?? theme.colorScheme.secondary;
    final Color focusColor = this.focusColor
      ?? floatingActionButtonTheme.focusColor
      ?? theme.focusColor;
    final Color hoverColor = this.hoverColor
      ?? floatingActionButtonTheme.hoverColor
      ?? theme.hoverColor;
464 465 466
    final Color splashColor = this.splashColor
      ?? floatingActionButtonTheme.splashColor
      ?? theme.splashColor;
467 468 469
    final double elevation = this.elevation
      ?? floatingActionButtonTheme.elevation
      ?? _defaultElevation;
470 471 472 473 474 475
    final double focusElevation = this.focusElevation
      ?? floatingActionButtonTheme.focusElevation
      ?? _defaultFocusElevation;
    final double hoverElevation = this.hoverElevation
      ?? floatingActionButtonTheme.hoverElevation
      ?? _defaultHoverElevation;
476 477 478 479 480 481 482 483
    final double disabledElevation = this.disabledElevation
      ?? floatingActionButtonTheme.disabledElevation
      ?? elevation;
    final double highlightElevation = this.highlightElevation
      ?? floatingActionButtonTheme.highlightElevation
      ?? _defaultHighlightElevation;
    final MaterialTapTargetSize materialTapTargetSize = this.materialTapTargetSize
      ?? theme.materialTapTargetSize;
484
    final TextStyle textStyle = theme.textTheme.button.copyWith(
485 486 487 488 489 490 491
      color: foregroundColor,
      letterSpacing: 1.2,
    );
    final ShapeBorder shape = this.shape
      ?? floatingActionButtonTheme.shape
      ?? (isExtended ? _defaultExtendedShape : _defaultShape);

492
    Widget result = RawMaterialButton(
493
      onPressed: onPressed,
494
      mouseCursor: mouseCursor,
495
      elevation: elevation,
496 497
      focusElevation: focusElevation,
      hoverElevation: hoverElevation,
498 499 500
      highlightElevation: highlightElevation,
      disabledElevation: disabledElevation,
      constraints: _sizeConstraints,
501 502
      materialTapTargetSize: materialTapTargetSize,
      fillColor: backgroundColor,
503 504
      focusColor: focusColor,
      hoverColor: hoverColor,
505
      splashColor: splashColor,
506
      textStyle: textStyle,
507
      shape: shape,
508
      clipBehavior: clipBehavior,
509
      focusNode: focusNode,
510
      autofocus: autofocus,
511
      child: child,
512 513
    );

514
    if (tooltip != null) {
515 516 517
      result = Tooltip(
        message: tooltip,
        child: result,
518 519 520
      );
    }

521
    if (heroTag != null) {
522
      result = Hero(
523
        tag: heroTag,
524 525 526 527
        child: result,
      );
    }

528
    return MergeSemantics(child: result);
529
  }
530 531 532 533 534 535

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(ObjectFlagProperty<VoidCallback>('onPressed', onPressed, ifNull: 'disabled'));
    properties.add(StringProperty('tooltip', tooltip, defaultValue: null));
536 537 538 539
    properties.add(ColorProperty('foregroundColor', foregroundColor, defaultValue: null));
    properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
    properties.add(ColorProperty('focusColor', focusColor, defaultValue: null));
    properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null));
540
    properties.add(ColorProperty('splashColor', splashColor, defaultValue: null));
541
    properties.add(ObjectFlagProperty<Object>('heroTag', heroTag, ifPresent: 'hero'));
542 543 544 545 546
    properties.add(DoubleProperty('elevation', elevation, defaultValue: null));
    properties.add(DoubleProperty('focusElevation', focusElevation, defaultValue: null));
    properties.add(DoubleProperty('hoverElevation', hoverElevation, defaultValue: null));
    properties.add(DoubleProperty('highlightElevation', highlightElevation, defaultValue: null));
    properties.add(DoubleProperty('disabledElevation', disabledElevation, defaultValue: null));
547 548 549 550 551
    properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
    properties.add(FlagProperty('isExtended', value: isExtended, ifTrue: 'extended'));
    properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, defaultValue: null));
  }
552
}
553 554 555 556 557 558 559 560 561 562 563 564 565 566

// This widget's size matches its child's size unless its constraints
// force it to be larger or smaller. The child is centered.
//
// Used to encapsulate extended FABs whose size is fixed, using Row
// and MainAxisSize.min, to be as wide as their label and icon.
class _ChildOverflowBox extends SingleChildRenderObjectWidget {
  const _ChildOverflowBox({
    Key key,
    Widget child,
  }) : super(key: key, child: child);

  @override
  _RenderChildOverflowBox createRenderObject(BuildContext context) {
567
    return _RenderChildOverflowBox(
568 569 570 571 572 573
      textDirection: Directionality.of(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderChildOverflowBox renderObject) {
574
    renderObject.textDirection = Directionality.of(context);
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  }
}

class _RenderChildOverflowBox extends RenderAligningShiftedBox {
  _RenderChildOverflowBox({
    RenderBox child,
    TextDirection textDirection,
  }) : super(child: child, alignment: Alignment.center, textDirection: textDirection);

  @override
  double computeMinIntrinsicWidth(double height) => 0.0;

  @override
  double computeMinIntrinsicHeight(double width) => 0.0;

  @override
  void performLayout() {
592
    final BoxConstraints constraints = this.constraints;
593 594
    if (child != null) {
      child.layout(const BoxConstraints(), parentUsesSize: true);
595
      size = Size(
596 597 598 599 600 601 602 603 604
        math.max(constraints.minWidth, math.min(constraints.maxWidth, child.size.width)),
        math.max(constraints.minHeight, math.min(constraints.maxHeight, child.size.height)),
      );
      alignChild();
    } else {
      size = constraints.biggest;
    }
  }
}