floating_action_button.dart 21.7 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
import 'dart:math' as math;

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

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

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

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

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

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

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

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

223
  /// The widget below this widget in the tree.
224 225
  ///
  /// Typically an [Icon].
226
  final Widget child;
227

228 229 230 231
  /// 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
232
  final String tooltip;
233

234
  /// The default foreground color for icons and text within the button.
235
  ///
236 237 238 239 240 241 242 243 244
  /// 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.
245 246
  final Color foregroundColor;

247
  /// The button's background color.
248
  ///
249 250 251 252
  /// 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.
253
  final Color backgroundColor;
254

255 256 257 258 259 260 261 262 263 264 265
  /// 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;

266 267 268 269 270 271
  /// 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;

272 273 274
  /// The tag to apply to the button's [Hero] widget.
  ///
  /// Defaults to a tag that matches other floating action buttons.
275 276 277 278 279 280 281 282 283
  ///
  /// 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.
284 285
  final Object heroTag;

286
  /// The callback that is called when the button is tapped or otherwise activated.
287 288
  ///
  /// If this is set to null, the button will be disabled.
289
  final VoidCallback onPressed;
290

291
  /// The z-coordinate at which to place this button relative to its parent.
292
  ///
293 294 295 296
  /// 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.
297 298 299 300 301
  ///
  /// See also:
  ///
  ///  * [highlightElevation], the elevation when the button is pressed.
  ///  * [disabledElevation], the elevation when the button is disabled.
302
  final double elevation;
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  /// 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;

334 335 336 337
  /// 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.
338 339
  ///
  /// Defaults to 12, the appropriate elevation for floating action buttons
340
  /// while they are being touched. The value is always non-negative.
341 342 343 344
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
345
  final double highlightElevation;
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
  /// 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;

362 363 364 365
  /// 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
366
  /// and width of 40.0 logical pixels with a layout width and height of 48.0
367 368 369
  /// 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
370
  final bool mini;
371

372 373 374 375 376 377 378
  /// 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;

379
  /// {@macro flutter.widgets.Clip}
380 381
  ///
  /// Defaults to [Clip.none], and must not be null.
382 383
  final Clip clipBehavior;

384 385 386 387 388 389 390 391 392 393 394
  /// 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;

395
  /// {@macro flutter.widgets.Focus.focusNode}
396 397
  final FocusNode focusNode;

398 399 400
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

401 402 403 404 405 406
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [ThemeData.materialTapTargetSize].
  ///
  /// See also:
  ///
407
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
408 409
  final MaterialTapTargetSize materialTapTargetSize;

410 411
  final BoxConstraints _sizeConstraints;

412
  static const double _defaultElevation = 6;
413 414 415 416
  // TODO(gspencer): verify focus and hover elevation values are correct
  // according to spec.
  static const double _defaultFocusElevation = 8;
  static const double _defaultHoverElevation = 10;
417 418 419 420
  static const double _defaultHighlightElevation = 12;
  static const ShapeBorder _defaultShape = CircleBorder();
  static const ShapeBorder _defaultExtendedShape = StadiumBorder();

421
  @override
422
  Widget build(BuildContext context) {
423
    final ThemeData theme = Theme.of(context);
424 425
    final FloatingActionButtonThemeData floatingActionButtonTheme = theme.floatingActionButtonTheme;

426 427 428 429 430 431 432 433 434 435 436 437 438
    // 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 '
439
          'https://flutter.dev/go/remove-fab-accent-theme-dependency. '
440 441 442 443 444
          'This feature was deprecated after v1.13.2.'
        );
      }
    }

445 446 447
    final Color foregroundColor = this.foregroundColor
      ?? floatingActionButtonTheme.foregroundColor
      ?? theme.colorScheme.onSecondary;
448 449 450 451 452 453 454 455 456
    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;
457 458 459
    final Color splashColor = this.splashColor
      ?? floatingActionButtonTheme.splashColor
      ?? theme.splashColor;
460 461 462
    final double elevation = this.elevation
      ?? floatingActionButtonTheme.elevation
      ?? _defaultElevation;
463 464 465 466 467 468
    final double focusElevation = this.focusElevation
      ?? floatingActionButtonTheme.focusElevation
      ?? _defaultFocusElevation;
    final double hoverElevation = this.hoverElevation
      ?? floatingActionButtonTheme.hoverElevation
      ?? _defaultHoverElevation;
469 470 471 472 473 474 475 476
    final double disabledElevation = this.disabledElevation
      ?? floatingActionButtonTheme.disabledElevation
      ?? elevation;
    final double highlightElevation = this.highlightElevation
      ?? floatingActionButtonTheme.highlightElevation
      ?? _defaultHighlightElevation;
    final MaterialTapTargetSize materialTapTargetSize = this.materialTapTargetSize
      ?? theme.materialTapTargetSize;
477
    final TextStyle textStyle = theme.textTheme.button.copyWith(
478 479 480 481 482 483 484
      color: foregroundColor,
      letterSpacing: 1.2,
    );
    final ShapeBorder shape = this.shape
      ?? floatingActionButtonTheme.shape
      ?? (isExtended ? _defaultExtendedShape : _defaultShape);

485
    Widget result = RawMaterialButton(
486 487
      onPressed: onPressed,
      elevation: elevation,
488 489
      focusElevation: focusElevation,
      hoverElevation: hoverElevation,
490 491 492
      highlightElevation: highlightElevation,
      disabledElevation: disabledElevation,
      constraints: _sizeConstraints,
493 494
      materialTapTargetSize: materialTapTargetSize,
      fillColor: backgroundColor,
495 496
      focusColor: focusColor,
      hoverColor: hoverColor,
497
      splashColor: splashColor,
498
      textStyle: textStyle,
499
      shape: shape,
500
      clipBehavior: clipBehavior,
501
      focusNode: focusNode,
502
      autofocus: autofocus,
503
      child: child,
504 505
    );

506
    if (tooltip != null) {
507 508 509
      result = Tooltip(
        message: tooltip,
        child: result,
510 511 512
      );
    }

513
    if (heroTag != null) {
514
      result = Hero(
515
        tag: heroTag,
516 517 518 519
        child: result,
      );
    }

520
    return MergeSemantics(child: result);
521
  }
522 523 524 525 526 527

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(ObjectFlagProperty<VoidCallback>('onPressed', onPressed, ifNull: 'disabled'));
    properties.add(StringProperty('tooltip', tooltip, defaultValue: null));
528 529 530 531
    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));
532
    properties.add(ColorProperty('splashColor', splashColor, defaultValue: null));
533
    properties.add(ObjectFlagProperty<Object>('heroTag', heroTag, ifPresent: 'hero'));
534 535 536 537 538
    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));
539 540 541 542 543
    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));
  }
544
}
545 546 547 548 549 550 551 552 553 554 555 556 557 558

// 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) {
559
    return _RenderChildOverflowBox(
560 561 562 563 564 565
      textDirection: Directionality.of(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderChildOverflowBox renderObject) {
566
    renderObject.textDirection = Directionality.of(context);
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  }
}

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() {
584
    final BoxConstraints constraints = this.constraints;
585 586
    if (child != null) {
      child.layout(const BoxConstraints(), parentUsesSize: true);
587
      size = Size(
588 589 590 591 592 593 594 595 596
        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;
    }
  }
}