button.dart 17.6 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/gestures.dart';
9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/widgets.dart';
11

12
import 'button_theme.dart';
13
import 'constants.dart';
14 15
import 'ink_well.dart';
import 'material.dart';
16
import 'material_state.dart';
17
import 'theme.dart';
18
import 'theme_data.dart';
19

20 21
/// Creates a button based on [Semantics], [Material], and [InkWell]
/// widgets.
22
///
23 24 25 26
/// This class does not use the current [Theme] or [ButtonTheme] to
/// compute default values for unspecified parameters. It's intended to
/// be used for custom Material buttons that optionally incorporate defaults
/// from the themes or from app-specific sources.
27
///
28 29 30 31 32
/// [RaisedButton] and [FlatButton] configure a [RawMaterialButton] based
/// on the current [Theme] and [ButtonTheme].
class RawMaterialButton extends StatefulWidget {
  /// Create a button based on [Semantics], [Material], and [InkWell] widgets.
  ///
33
  /// The [shape], [elevation], [focusElevation], [hoverElevation],
34 35 36
  /// [highlightElevation], [disabledElevation], [padding], [constraints],
  /// [autofocus], and [clipBehavior] arguments must not be null. Additionally,
  /// [elevation], [focusElevation], [hoverElevation], [highlightElevation], and
37
  /// [disabledElevation] must be non-negative.
38
  const RawMaterialButton({
39
    Key key,
40
    @required this.onPressed,
41
    this.onLongPress,
42
    this.onHighlightChanged,
43 44
    this.textStyle,
    this.fillColor,
45 46
    this.focusColor,
    this.hoverColor,
47 48
    this.highlightColor,
    this.splashColor,
49
    this.elevation = 2.0,
50 51
    this.focusElevation = 4.0,
    this.hoverElevation = 4.0,
52 53 54
    this.highlightElevation = 8.0,
    this.disabledElevation = 0.0,
    this.padding = EdgeInsets.zero,
55
    this.visualDensity = const VisualDensity(),
56 57 58
    this.constraints = const BoxConstraints(minWidth: 88.0, minHeight: 36.0),
    this.shape = const RoundedRectangleBorder(),
    this.animationDuration = kThemeChangeDuration,
59
    this.clipBehavior = Clip.none,
60
    this.focusNode,
61
    this.autofocus = false,
62
    MaterialTapTargetSize materialTapTargetSize,
63
    this.child,
64
    this.enableFeedback = true,
65
  }) : materialTapTargetSize = materialTapTargetSize ?? MaterialTapTargetSize.padded,
66
       assert(shape != null),
67
       assert(elevation != null && elevation >= 0.0),
68 69
       assert(focusElevation != null && focusElevation >= 0.0),
       assert(hoverElevation != null && hoverElevation >= 0.0),
70 71
       assert(highlightElevation != null && highlightElevation >= 0.0),
       assert(disabledElevation != null && disabledElevation >= 0.0),
72 73
       assert(padding != null),
       assert(constraints != null),
74
       assert(animationDuration != null),
75
       assert(clipBehavior != null),
76
       assert(autofocus != null),
77 78 79 80
       super(key: key);

  /// Called when the button is tapped or otherwise activated.
  ///
81 82 83 84 85
  /// If this callback and [onLongPress] are null, then the button will be disabled.
  ///
  /// See also:
  ///
  ///  * [enabled], which is true if the button is enabled.
86
  final VoidCallback onPressed;
87

88 89 90 91 92 93 94 95 96
  /// Called when the button is long-pressed.
  ///
  /// If this callback and [onPressed] are null, then the button will be disabled.
  ///
  /// See also:
  ///
  ///  * [enabled], which is true if the button is enabled.
  final VoidCallback onLongPress;

97 98
  /// Called by the underlying [InkWell] widget's [InkWell.onHighlightChanged]
  /// callback.
99 100 101 102
  ///
  /// If [onPressed] changes from null to non-null while a gesture is ongoing,
  /// this can fire during the build phase (in which case calling
  /// [State.setState] is not allowed).
103 104
  final ValueChanged<bool> onHighlightChanged;

105 106
  /// Defines the default text style, with [Material.textStyle], for the
  /// button's [child].
107
  ///
108
  /// If [textStyle.color] is a [MaterialStateProperty<Color>], [MaterialStateProperty.resolve]
109 110 111 112 113 114
  /// is used for the following [MaterialState]s:
  ///
  ///  * [MaterialState.pressed].
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
115 116 117 118 119
  final TextStyle textStyle;

  /// The color of the button's [Material].
  final Color fillColor;

120 121 122 123 124 125
  /// The color for the button's [Material] when it has the input focus.
  final Color focusColor;

  /// The color for the button's [Material] when a pointer is hovering over it.
  final Color hoverColor;

126 127 128 129 130 131 132 133
  /// The highlight color for the button's [InkWell].
  final Color highlightColor;

  /// The splash color for the button's [InkWell].
  final Color splashColor;

  /// The elevation for the button's [Material] when the button
  /// is [enabled] but not pressed.
134
  ///
135
  /// Defaults to 2.0. The value is always non-negative.
136 137 138 139
  ///
  /// See also:
  ///
  ///  * [highlightElevation], the default elevation.
140 141 142
  ///  * [hoverElevation], the elevation when a pointer is hovering over the
  ///    button.
  ///  * [focusElevation], the elevation when the button is focused.
143 144
  ///  * [disabledElevation], the elevation when the button is disabled.
  final double elevation;
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
  /// The elevation for the button's [Material] when the button
  /// is [enabled] and a pointer is hovering over it.
  ///
  /// Defaults to 4.0. The value is always non-negative.
  ///
  /// If the button is [enabled], and being pressed (in the highlighted state),
  /// then the [highlightElevation] take precedence over the [hoverElevation].
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
  ///  * [focusElevation], the elevation when the button is focused.
  ///  * [disabledElevation], the elevation when the button is disabled.
  ///  * [highlightElevation], the elevation when the button is pressed.
  final double hoverElevation;

  /// The elevation for the button's [Material] when the button
  /// is [enabled] and has the input focus.
  ///
  /// Defaults to 4.0. The value is always non-negative.
  ///
  /// If the button is [enabled], and being pressed (in the highlighted state),
  /// or a mouse cursor is hovering over the button, then the [hoverElevation]
  /// and [highlightElevation] take precedence over the [focusElevation].
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
  ///  * [hoverElevation], the elevation when a pointer is hovering over the
  ///    button.
  ///  * [disabledElevation], the elevation when the button is disabled.
  ///  * [highlightElevation], the elevation when the button is pressed.
  final double focusElevation;

180 181
  /// The elevation for the button's [Material] when the button
  /// is [enabled] and pressed.
182
  ///
183
  /// Defaults to 8.0. The value is always non-negative.
184 185 186 187
  ///
  /// See also:
  ///
  ///  * [elevation], the default elevation.
188
  ///  * [hoverElevation], the elevation when a pointer is hovering over the
189
  ///    button.
190
  ///  * [focusElevation], the elevation when the button is focused.
191 192
  ///  * [disabledElevation], the elevation when the button is disabled.
  final double highlightElevation;
193

194 195
  /// The elevation for the button's [Material] when the button
  /// is not [enabled].
196
  ///
197
  /// Defaults to 0.0. The value is always non-negative.
198
  ///
199 200
  /// See also:
  ///
201
  ///  * [elevation], the default elevation.
202
  ///  * [hoverElevation], the elevation when a pointer is hovering over the
203
  ///    button.
204
  ///  * [focusElevation], the elevation when the button is focused.
205 206 207 208
  ///  * [highlightElevation], the elevation when the button is pressed.
  final double disabledElevation;

  /// The internal padding for the button's [child].
209
  final EdgeInsetsGeometry padding;
210

211 212 213 214 215 216 217 218 219 220
  /// Defines how compact the button's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
  ///  * [ThemeData.visualDensity], which specifies the [visualDensity] for all widgets
  ///    within a [Theme].
  final VisualDensity visualDensity;

221
  /// Defines the button's size.
222
  ///
223 224 225 226
  /// Typically used to constrain the button's minimum size.
  final BoxConstraints constraints;

  /// The shape of the button's [Material].
227
  ///
228 229
  /// 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.
230 231 232 233 234 235 236 237
  ///
  /// If [shape] is a [MaterialStateProperty<ShapeBorder>], [MaterialStateProperty.resolve]
  /// is used for the following [MaterialState]s:
  ///
  /// * [MaterialState.pressed].
  /// * [MaterialState.hovered].
  /// * [MaterialState.focused].
  /// * [MaterialState.disabled].
238 239
  final ShapeBorder shape;

240 241 242 243 244
  /// Defines the duration of animated changes for [shape] and [elevation].
  ///
  /// The default value is [kThemeChangeDuration].
  final Duration animationDuration;

245 246 247 248 249 250
  /// Typically the button's label.
  final Widget child;

  /// Whether the button is enabled or disabled.
  ///
  /// Buttons are disabled by default. To enable a button, set its [onPressed]
251 252
  /// or [onLongPress] properties to a non-null value.
  bool get enabled => onPressed != null || onLongPress != null;
253

254 255 256 257 258 259
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [MaterialTapTargetSize.padded].
  ///
  /// See also:
  ///
260
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
261 262
  final MaterialTapTargetSize materialTapTargetSize;

263
  /// {@macro flutter.widgets.Focus.focusNode}
264 265
  final FocusNode focusNode;

266 267 268
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

269
  /// {@macro flutter.widgets.Clip}
270 271
  ///
  /// Defaults to [Clip.none], and must not be null.
272 273
  final Clip clipBehavior;

274 275 276 277 278 279 280 281 282 283
  /// Whether detected gestures should provide acoustic and/or haptic feedback.
  ///
  /// For example, on Android a tap will produce a clicking sound and a
  /// long-press will produce a short vibration, when feedback is enabled.
  ///
  /// See also:
  ///
  ///  * [Feedback] for providing platform-specific feedback to certain actions.
  final bool enableFeedback;

284
  @override
285
  _RawMaterialButtonState createState() => _RawMaterialButtonState();
286 287 288
}

class _RawMaterialButtonState extends State<RawMaterialButton> {
289 290 291 292 293 294 295 296 297 298
  final Set<MaterialState> _states = <MaterialState>{};

  bool get _hovered => _states.contains(MaterialState.hovered);
  bool get _focused => _states.contains(MaterialState.focused);
  bool get _pressed => _states.contains(MaterialState.pressed);
  bool get _disabled => _states.contains(MaterialState.disabled);

  void _updateState(MaterialState state, bool value) {
    value ? _states.add(state) : _states.remove(state);
  }
299

300
  void _handleHighlightChanged(bool value) {
301
    if (_pressed != value) {
302
      setState(() {
303
        _updateState(MaterialState.pressed, value);
304
        if (widget.onHighlightChanged != null) {
305
          widget.onHighlightChanged(value);
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
  void _handleHoveredChanged(bool value) {
    if (_hovered != value) {
      setState(() {
        _updateState(MaterialState.hovered, value);
      });
    }
  }

  void _handleFocusedChanged(bool value) {
    if (_focused != value) {
      setState(() {
        _updateState(MaterialState.focused, value);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _updateState(MaterialState.disabled, !widget.enabled);
  }

333 334 335
  @override
  void didUpdateWidget(RawMaterialButton oldWidget) {
    super.didUpdateWidget(oldWidget);
336 337 338 339 340 341 342
    _updateState(MaterialState.disabled, !widget.enabled);
    // If the button is disabled while a press gesture is currently ongoing,
    // InkWell makes a call to handleHighlightChanged. This causes an exception
    // because it calls setState in the middle of a build. To preempt this, we
    // manually update pressed to false when this situation occurs.
    if (_disabled && _pressed) {
      _handleHighlightChanged(false);
343 344 345
    }
  }

346 347 348 349
  double get _effectiveElevation {
    // These conditionals are in order of precedence, so be careful about
    // reorganizing them.
    if (_disabled) {
350
      return widget.disabledElevation;
351
    }
352 353 354 355 356 357 358 359 360 361
    if (_pressed) {
      return widget.highlightElevation;
    }
    if (_hovered) {
      return widget.hoverElevation;
    }
    if (_focused) {
      return widget.focusElevation;
    }
    return widget.elevation;
362 363
  }

364
  @override
365
  Widget build(BuildContext context) {
366 367
    final Color effectiveTextColor = MaterialStateProperty.resolveAs<Color>(widget.textStyle?.color, _states);
    final ShapeBorder effectiveShape =  MaterialStateProperty.resolveAs<ShapeBorder>(widget.shape, _states);
368
    final Offset densityAdjustment = widget.visualDensity.baseSizeAdjustment;
369
    final BoxConstraints effectiveConstraints = widget.visualDensity.effectiveConstraints(widget.constraints);
370 371 372 373 374 375 376 377
    final EdgeInsetsGeometry padding = widget.padding.add(
      EdgeInsets.only(
        left: densityAdjustment.dx,
        top: densityAdjustment.dy,
        right: densityAdjustment.dx,
        bottom: densityAdjustment.dy,
      ),
    ).clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity);
378

379
    final Widget result = ConstrainedBox(
380
      constraints: effectiveConstraints,
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
      child: Material(
        elevation: _effectiveElevation,
        textStyle: widget.textStyle?.copyWith(color: effectiveTextColor),
        shape: effectiveShape,
        color: widget.fillColor,
        type: widget.fillColor == null ? MaterialType.transparency : MaterialType.button,
        animationDuration: widget.animationDuration,
        clipBehavior: widget.clipBehavior,
        child: InkWell(
          focusNode: widget.focusNode,
          canRequestFocus: widget.enabled,
          onFocusChange: _handleFocusedChanged,
          autofocus: widget.autofocus,
          onHighlightChanged: _handleHighlightChanged,
          splashColor: widget.splashColor,
          highlightColor: widget.highlightColor,
          focusColor: widget.focusColor,
          hoverColor: widget.hoverColor,
          onHover: _handleHoveredChanged,
          onTap: widget.onPressed,
401
          onLongPress: widget.onLongPress,
402
          enableFeedback: widget.enableFeedback,
403 404 405 406
          customBorder: effectiveShape,
          child: IconTheme.merge(
            data: IconThemeData(color: effectiveTextColor),
            child: Container(
407
              padding: padding,
408 409 410 411
              child: Center(
                widthFactor: 1.0,
                heightFactor: 1.0,
                child: widget.child,
412 413 414 415 416 417
              ),
            ),
          ),
        ),
      ),
    );
418
    Size minSize;
419 420
    switch (widget.materialTapTargetSize) {
      case MaterialTapTargetSize.padded:
421 422 423 424 425 426
        minSize = Size(
          kMinInteractiveDimension + densityAdjustment.dx,
          kMinInteractiveDimension + densityAdjustment.dy,
        );
        assert(minSize.width >= 0.0);
        assert(minSize.height >= 0.0);
427 428
        break;
      case MaterialTapTargetSize.shrinkWrap:
429
        minSize = Size.zero;
430
        break;
431 432
    }

433
    return Semantics(
434 435 436
      container: true,
      button: true,
      enabled: widget.enabled,
437
      child: _InputPadding(
438 439 440
        minSize: minSize,
        child: result,
      ),
441
    );
442
  }
443 444
}

445
/// A widget to pad the area around a [MaterialButton]'s inner [Material].
446 447 448
///
/// Redirect taps that occur in the padded area around the child to the center
/// of the child. This increases the size of the button and the button's
449 450 451
/// "tap target", but not its material or its ink splashes.
class _InputPadding extends SingleChildRenderObjectWidget {
  const _InputPadding({
452 453
    Key key,
    Widget child,
454
    this.minSize,
455 456
  }) : super(key: key, child: child);

457
  final Size minSize;
458 459 460

  @override
  RenderObject createRenderObject(BuildContext context) {
461
    return _RenderInputPadding(minSize);
462 463 464
  }

  @override
465 466
  void updateRenderObject(BuildContext context, covariant _RenderInputPadding renderObject) {
    renderObject.minSize = minSize;
467 468 469
  }
}

470
class _RenderInputPadding extends RenderShiftedBox {
471
  _RenderInputPadding(this._minSize, [RenderBox child]) : super(child);
472 473 474 475 476 477 478 479 480 481 482 483 484

  Size get minSize => _minSize;
  Size _minSize;
  set minSize(Size value) {
    if (_minSize == value)
      return;
    _minSize = value;
    markNeedsLayout();
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    if (child != null)
Ian Hickson's avatar
Ian Hickson committed
485
      return math.max(child.getMinIntrinsicWidth(height), minSize.width);
486 487 488 489 490 491
    return 0.0;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    if (child != null)
Ian Hickson's avatar
Ian Hickson committed
492
      return math.max(child.getMinIntrinsicHeight(width), minSize.height);
493 494 495 496 497 498
    return 0.0;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    if (child != null)
Ian Hickson's avatar
Ian Hickson committed
499
      return math.max(child.getMaxIntrinsicWidth(height), minSize.width);
500 501 502 503 504 505
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    if (child != null)
Ian Hickson's avatar
Ian Hickson committed
506
      return math.max(child.getMaxIntrinsicHeight(width), minSize.height);
507 508 509 510 511 512 513 514 515
    return 0.0;
  }

  @override
  void performLayout() {
    if (child != null) {
      child.layout(constraints, parentUsesSize: true);
      final double height = math.max(child.size.width, minSize.width);
      final double width = math.max(child.size.height, minSize.height);
516
      size = constraints.constrain(Size(height, width));
517 518
      final BoxParentData childParentData = child.parentData as BoxParentData;
      childParentData.offset = Alignment.center.alongOffset(size - child.size as Offset);
519 520 521 522
    } else {
      size = Size.zero;
    }
  }
523 524

  @override
525 526 527 528 529 530 531 532 533 534 535 536 537
  bool hitTest(BoxHitTestResult result, { Offset position }) {
    if (super.hitTest(result, position: position)) {
      return true;
    }
    final Offset center = child.size.center(Offset.zero);
    return result.addWithRawTransform(
      transform: MatrixUtils.forceToPoint(center),
      position: center,
      hitTest: (BoxHitTestResult result, Offset position) {
        assert(position == center);
        return child.hitTest(result, position: center);
      },
    );
538 539
  }
}