button.dart 8.38 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

8
import 'colors.dart';
9
import 'constants.dart';
xster's avatar
xster committed
10
import 'theme.dart';
xster's avatar
xster committed
11

xster's avatar
xster committed
12
// Measured against iOS 12 in Xcode.
13 14
const EdgeInsets _kButtonPadding = EdgeInsets.all(16.0);
const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric(
15
  vertical: 14.0,
16 17
  horizontal: 64.0,
);
18

Adam Barth's avatar
Adam Barth committed
19
/// An iOS-style button.
20 21 22 23 24 25
///
/// Takes in a text or an icon that fades out and in on touch. May optionally have a
/// background.
///
/// See also:
///
26
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/buttons/>
27
class CupertinoButton extends StatefulWidget {
Adam Barth's avatar
Adam Barth committed
28
  /// Creates an iOS-style button.
29
  const CupertinoButton({
30
    Key key,
31 32 33
    @required this.child,
    this.padding,
    this.color,
34
    this.disabledColor = CupertinoColors.quaternarySystemFill,
35
    this.minSize = kMinInteractiveDimensionCupertino,
36
    this.pressedOpacity = 0.4,
37
    this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),
38
    @required this.onPressed,
xster's avatar
xster committed
39
  }) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),
40
       assert(disabledColor != null),
41 42
       _filled = false,
       super(key: key);
xster's avatar
xster committed
43 44 45 46 47 48 49 50

  /// Creates an iOS-style button with a filled background.
  ///
  /// The background color is derived from the [CupertinoTheme]'s `primaryColor`.
  ///
  /// To specify a custom background color, use the [color] argument of the
  /// default constructor.
  const CupertinoButton.filled({
51
    Key key,
xster's avatar
xster committed
52 53
    @required this.child,
    this.padding,
54
    this.disabledColor = CupertinoColors.quaternarySystemFill,
55
    this.minSize = kMinInteractiveDimensionCupertino,
56
    this.pressedOpacity = 0.4,
xster's avatar
xster committed
57 58 59
    this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),
    @required this.onPressed,
  }) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),
60
       assert(disabledColor != null),
xster's avatar
xster committed
61
       color = null,
62 63
       _filled = true,
       super(key: key);
64 65 66 67 68 69 70 71 72

  /// The widget below this widget in the tree.
  ///
  /// Typically a [Text] widget.
  final Widget child;

  /// The amount of space to surround the child inside the bounds of the button.
  ///
  /// Defaults to 16.0 pixels.
73
  final EdgeInsetsGeometry padding;
74 75 76 77

  /// The color of the button's background.
  ///
  /// Defaults to null which produces a button with no background or border.
xster's avatar
xster committed
78 79 80
  ///
  /// Defaults to the [CupertinoTheme]'s `primaryColor` when the
  /// [CupertinoButton.filled] constructor is used.
81 82
  final Color color;

83 84 85 86
  /// The color of the button's background when the button is disabled.
  ///
  /// Ignored if the [CupertinoButton] doesn't also have a [color].
  ///
87 88
  /// Defaults to [CupertinoColors.quaternarySystemFill] when [color] is
  /// specified. Must not be null.
89 90
  final Color disabledColor;

91 92 93 94 95
  /// The callback that is called when the button is tapped or otherwise activated.
  ///
  /// If this is set to null, the button will be disabled.
  final VoidCallback onPressed;

96 97
  /// Minimum size of the button.
  ///
98 99
  /// Defaults to kMinInteractiveDimensionCupertino which the iOS Human
  /// Interface Guidelines recommends as the minimum tappable area.
100 101
  final double minSize;

102 103 104
  /// The opacity that the button will fade to when it is pressed.
  /// The button will have an opacity of 1.0 when it is not pressed.
  ///
105
  /// This defaults to 0.4. If null, opacity will not change on pressed if using
xster's avatar
xster committed
106
  /// your own custom effects is desired.
107 108
  final double pressedOpacity;

xster's avatar
xster committed
109 110 111 112 113
  /// The radius of the button's corners when it has a background color.
  ///
  /// Defaults to round corners of 8 logical pixels.
  final BorderRadius borderRadius;

xster's avatar
xster committed
114 115
  final bool _filled;

116 117 118 119 120
  /// Whether the button is enabled or disabled. Buttons are disabled by default. To
  /// enable a button, set its [onPressed] property to a non-null value.
  bool get enabled => onPressed != null;

  @override
121
  _CupertinoButtonState createState() => _CupertinoButtonState();
122 123

  @override
124 125
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
126
    properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'disabled'));
127 128 129 130 131
  }
}

class _CupertinoButtonState extends State<CupertinoButton> with SingleTickerProviderStateMixin {
  // Eyeballed values. Feel free to tweak.
132 133
  static const Duration kFadeOutDuration = Duration(milliseconds: 10);
  static const Duration kFadeInDuration = Duration(milliseconds: 100);
134
  final Tween<double> _opacityTween = Tween<double>(begin: 1.0);
135 136

  AnimationController _animationController;
137
  Animation<double> _opacityAnimation;
138

139 140 141
  @override
  void initState() {
    super.initState();
142
    _animationController = AnimationController(
143
      duration: const Duration(milliseconds: 200),
144
      value: 0.0,
145 146
      vsync: this,
    );
147 148 149
    _opacityAnimation = _animationController
      .drive(CurveTween(curve: Curves.decelerate))
      .drive(_opacityTween);
150
    _setTween();
151 152
  }

153 154 155 156 157 158 159 160 161 162
  @override
  void didUpdateWidget(CupertinoButton old) {
    super.didUpdateWidget(old);
    _setTween();
  }

  void _setTween() {
    _opacityTween.end = widget.pressedOpacity ?? 1.0;
  }

163 164 165 166 167 168 169
  @override
  void dispose() {
    _animationController.dispose();
    _animationController = null;
    super.dispose();
  }

170 171 172 173 174 175 176 177 178 179 180 181 182 183
  bool _buttonHeldDown = false;

  void _handleTapDown(TapDownDetails event) {
    if (!_buttonHeldDown) {
      _buttonHeldDown = true;
      _animate();
    }
  }

  void _handleTapUp(TapUpDetails event) {
    if (_buttonHeldDown) {
      _buttonHeldDown = false;
      _animate();
    }
184 185
  }

186 187 188 189 190
  void _handleTapCancel() {
    if (_buttonHeldDown) {
      _buttonHeldDown = false;
      _animate();
    }
191 192
  }

193 194 195 196
  void _animate() {
    if (_animationController.isAnimating)
      return;
    final bool wasHeldDown = _buttonHeldDown;
197
    final TickerFuture ticker = _buttonHeldDown
198 199
        ? _animationController.animateTo(1.0, duration: kFadeOutDuration)
        : _animationController.animateTo(0.0, duration: kFadeInDuration);
200
    ticker.then<void>((void value) {
201 202 203
      if (mounted && wasHeldDown != _buttonHeldDown)
        _animate();
    });
204 205 206 207
  }

  @override
  Widget build(BuildContext context) {
208
    final bool enabled = widget.enabled;
209 210 211 212 213 214
    final CupertinoThemeData themeData = CupertinoTheme.of(context);
    final Color primaryColor = themeData.primaryColor;
    final Color backgroundColor = widget.color == null
      ? (widget._filled ? primaryColor : null)
      : CupertinoDynamicColor.resolve(widget.color, context);

xster's avatar
xster committed
215
    final Color foregroundColor = backgroundColor != null
216 217 218
      ? themeData.primaryContrastingColor
      : enabled
        ? primaryColor
219
        : CupertinoDynamicColor.resolve(CupertinoColors.placeholderText, context);
220 221

    final TextStyle textStyle = themeData.textTheme.textStyle.copyWith(color: foregroundColor);
222

223
    return GestureDetector(
224
      behavior: HitTestBehavior.opaque,
225 226 227 228
      onTapDown: enabled ? _handleTapDown : null,
      onTapUp: enabled ? _handleTapUp : null,
      onTapCancel: enabled ? _handleTapCancel : null,
      onTap: widget.onPressed,
229
      child: Semantics(
230
        button: true,
231
        child: ConstrainedBox(
232
          constraints: widget.minSize == null
233
            ? const BoxConstraints()
234
            : BoxConstraints(
235 236 237
              minWidth: widget.minSize,
              minHeight: widget.minSize,
            ),
238
          child: FadeTransition(
239
            opacity: _opacityAnimation,
240 241
            child: DecoratedBox(
              decoration: BoxDecoration(
242 243
                borderRadius: widget.borderRadius,
                color: backgroundColor != null && !enabled
244
                  ? CupertinoDynamicColor.resolve(widget.disabledColor, context)
245
                  : backgroundColor,
246
              ),
247
              child: Padding(
248 249 250
                padding: widget.padding ?? (backgroundColor != null
                  ? _kBackgroundButtonPadding
                  : _kButtonPadding),
251
                child: Center(
252 253
                  widthFactor: 1.0,
                  heightFactor: 1.0,
254
                  child: DefaultTextStyle(
xster's avatar
xster committed
255 256 257 258 259
                    style: textStyle,
                    child: IconTheme(
                      data: IconThemeData(color: foregroundColor),
                      child: widget.child,
                    ),
260
                  ),
261 262 263 264 265 266 267 268 269
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}