icon_button.dart 12.1 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5 6
import 'dart:math' as math;

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

10
import 'constants.dart';
11
import 'debug.dart';
12
import 'icons.dart';
13
import 'ink_well.dart';
14
import 'material.dart';
15
import 'theme.dart';
Hixie's avatar
Hixie committed
16
import 'tooltip.dart';
17

18
// Minimum logical pixel size of the IconButton.
19 20
// See: <https://material.io/design/usability/accessibility.html#layout-typography>.
const double _kMinButtonSize = kMinInteractiveDimension;
21

22
/// A material design icon button.
23 24
///
/// An icon button is a picture printed on a [Material] widget that reacts to
25
/// touches by filling with color (ink).
26
///
27 28
/// Icon buttons are commonly used in the [AppBar.actions] field, but they can
/// be used in many other places as well.
29
///
30 31
/// If the [onPressed] callback is null, then the button will be disabled and
/// will not react to touch.
32
///
33 34
/// Requires one of its ancestors to be a [Material] widget.
///
35 36 37
/// The hit region of an icon button will, if possible, be at least
/// kMinInteractiveDimension pixels in size, regardless of the actual
/// [iconSize], to satisfy the [touch target size](https://material.io/guidelines/layout/metrics-keylines.html#metrics-keylines-touch-target-size)
38 39
/// requirements in the Material Design specification. The [alignment] controls
/// how the icon itself is positioned within the hit region.
40
///
41
/// {@tool snippet --template=stateful_widget_scaffold_center}
42 43 44 45
///
/// This sample shows an `IconButton` that uses the Material icon "volume_up" to
/// increase the volume.
///
46 47
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/icon_button.png)
///
48 49 50
/// ```dart preamble
/// double _volume = 0.0;
/// ```
51 52
///
/// ```dart
53
/// Widget build(BuildContext context) {
54 55 56 57 58 59 60 61 62 63 64
///   return Column(
///     mainAxisSize: MainAxisSize.min,
///     children: <Widget>[
///       IconButton(
///         icon: Icon(Icons.volume_up),
///         tooltip: 'Increase volume by 10',
///         onPressed: () {
///           setState(() {
///             _volume += 10;
///           });
///         },
65
///       ),
66 67
///       Text('Volume : $_volume')
///     ],
68 69
///   );
/// }
70
/// ```
71
/// {@end-tool}
72
///
73 74 75 76 77 78 79 80 81 82 83 84
/// ### Adding a filled background
///
/// Icon buttons don't support specifying a background color or other
/// background decoration because typically the icon is just displayed
/// on top of the parent widget's background. Icon buttons that appear
/// in [AppBar.actions] are an example of this.
///
/// It's easy enough to create an icon button with a filled background
/// using the [Ink] widget. The [Ink] widget renders a decoration on
/// the underlying [Material] along with the splash and highlight
/// [InkResponse] contributed by descendant widgets.
///
85
/// {@tool snippet --template=stateless_widget_scaffold}
86 87 88 89 90 91
///
/// In this sample the icon button's background color is defined with an [Ink]
/// widget whose child is an [IconButton]. The icon button's filled background
/// is a light shade of blue, it's a filled circle, and it's as big as the
/// button is.
///
92 93
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/icon_button_background.png)
///
94
/// ```dart
95
/// Widget build(BuildContext context) {
96 97 98
///   return Material(
///     color: Colors.white,
///     child: Center(
99
///       child: Ink(
100
///         decoration: const ShapeDecoration(
101 102 103 104 105 106
///           color: Colors.lightBlue,
///           shape: CircleBorder(),
///         ),
///         child: IconButton(
///           icon: Icon(Icons.android),
///           color: Colors.white,
107
///           onPressed: () {},
108 109 110 111 112
///         ),
///       ),
///     ),
///   );
/// }
113 114 115
/// ```
/// {@end-tool}
///
116 117
/// See also:
///
118 119 120 121 122 123 124
///  * [Icons], a library of predefined icons.
///  * [BackButton], an icon button for a "back" affordance which adapts to the
///    current platform's conventions.
///  * [CloseButton], an icon button for closing pages.
///  * [AppBar], to show a toolbar at the top of an application.
///  * [RaisedButton] and [FlatButton], for buttons with text in them.
///  * [InkResponse] and [InkWell], for the ink splash effect itself.
125
class IconButton extends StatelessWidget {
126 127 128 129 130 131
  /// Creates an icon button.
  ///
  /// Icon buttons are commonly used in the [AppBar.actions] field, but they can
  /// be used in many other places as well.
  ///
  /// Requires one of its ancestors to be a [Material] widget.
132
  ///
133 134
  /// The [iconSize], [padding], [autofocus], and [alignment] arguments must not
  /// be null (though they each have default values).
135
  ///
Ian Hickson's avatar
Ian Hickson committed
136 137
  /// The [icon] argument must be specified, and is typically either an [Icon]
  /// or an [ImageIcon].
138 139
  const IconButton({
    Key key,
140 141 142
    this.iconSize = 24.0,
    this.padding = const EdgeInsets.all(8.0),
    this.alignment = Alignment.center,
143
    @required this.icon,
144
    this.color,
145 146
    this.focusColor,
    this.hoverColor,
147 148
    this.highlightColor,
    this.splashColor,
149
    this.disabledColor,
150
    @required this.onPressed,
151
    this.focusNode,
152
    this.autofocus = false,
153
    this.tooltip,
154 155 156
  }) : assert(iconSize != null),
       assert(padding != null),
       assert(alignment != null),
157
       assert(autofocus != null),
158 159
       assert(icon != null),
       super(key: key);
160

Adam Barth's avatar
Adam Barth committed
161
  /// The size of the icon inside the button.
162 163
  ///
  /// This property must not be null. It defaults to 24.0.
164 165 166 167 168 169 170
  ///
  /// The size given here is passed down to the widget in the [icon] property
  /// via an [IconTheme]. Setting the size here instead of in, for example, the
  /// [Icon.size] property allows the [IconButton] to size the splash area to
  /// fit the [Icon]. If you were to set the size of the [Icon] using
  /// [Icon.size] instead, then the [IconButton] would default to 24.0 and then
  /// the [Icon] itself would likely get clipped.
171
  final double iconSize;
Adam Barth's avatar
Adam Barth committed
172

173 174
  /// The padding around the button's icon. The entire padded icon will react
  /// to input gestures.
175 176
  ///
  /// This property must not be null. It defaults to 8.0 padding on all sides.
177
  final EdgeInsetsGeometry padding;
178 179

  /// Defines how the icon is positioned within the IconButton.
180
  ///
181
  /// This property must not be null. It defaults to [Alignment.center].
182 183 184 185 186 187 188
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
189
  final AlignmentGeometry alignment;
190

Ian Hickson's avatar
Ian Hickson committed
191 192
  /// The icon to display inside the button.
  ///
193
  /// The [Icon.size] and [Icon.color] of the icon is configured automatically
194
  /// based on the [iconSize] and [color] properties of _this_ widget using an
195 196
  /// [IconTheme] and therefore should not be explicitly given in the icon
  /// widget.
197 198
  ///
  /// This property must not be null.
Ian Hickson's avatar
Ian Hickson committed
199 200 201
  ///
  /// See [Icon], [ImageIcon].
  final Widget icon;
Adam Barth's avatar
Adam Barth committed
202

203 204 205 206 207 208 209 210 211 212
  /// The color for the button's icon when it has the input focus.
  ///
  /// Defaults to [ThemeData.focusColor] of the ambient theme.
  final Color focusColor;

  /// The color for the button's icon when a pointer is hovering over it.
  ///
  /// Defaults to [ThemeData.hoverColor] of the ambient theme.
  final Color hoverColor;

213
  /// The color to use for the icon inside the button, if the icon is enabled.
Ian Hickson's avatar
Ian Hickson committed
214
  /// Defaults to leaving this up to the [icon] widget.
215 216 217 218
  ///
  /// The icon is enabled if [onPressed] is not null.
  ///
  /// See also [disabledColor].
219 220
  ///
  /// ```dart
221 222 223 224
  /// IconButton(
  ///   color: Colors.blue,
  ///   onPressed: _handleTap,
  ///   icon: Icons.widgets,
225
  /// )
226
  /// ```
Adam Barth's avatar
Adam Barth committed
227
  final Color color;
228

229 230 231 232 233 234 235 236 237 238 239
  /// The primary color of the button when the button is in the down (pressed) state.
  /// The splash is represented as a circular overlay that appears above the
  /// [highlightColor] overlay. The splash overlay has a center point that matches
  /// the hit point of the user touch event. The splash overlay will expand to
  /// fill the button area if the touch is held for long enough time. If the splash
  /// color has transparency then the highlight and button color will show through.
  ///
  /// Defaults to the Theme's splash color, [ThemeData.splashColor].
  final Color splashColor;

  /// The secondary color of the button when the button is in the down (pressed)
240
  /// state. The highlight color is represented as a solid color that is overlaid over the
241 242 243 244 245 246
  /// button color (if any). If the highlight color has transparency, the button color
  /// will show through. The highlight fades in quickly as the button is held down.
  ///
  /// Defaults to the Theme's highlight color, [ThemeData.highlightColor].
  final Color highlightColor;

247 248 249 250 251 252 253 254
  /// The color to use for the icon inside the button, if the icon is disabled.
  /// Defaults to the [ThemeData.disabledColor] of the current [Theme].
  ///
  /// The icon is disabled if [onPressed] is null.
  ///
  /// See also [color].
  final Color disabledColor;

255
  /// The callback that is called when the button is tapped or otherwise activated.
256 257
  ///
  /// If this is set to null, the button will be disabled.
258
  final VoidCallback onPressed;
Adam Barth's avatar
Adam Barth committed
259

260
  /// {@macro flutter.widgets.Focus.focusNode}
261 262
  final FocusNode focusNode;

263 264 265
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

Adam Barth's avatar
Adam Barth committed
266 267 268 269
  /// 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.
Hixie's avatar
Hixie committed
270
  final String tooltip;
271

272
  @override
273
  Widget build(BuildContext context) {
274
    assert(debugCheckHasMaterial(context));
275 276 277 278 279
    Color currentColor;
    if (onPressed != null)
      currentColor = color;
    else
      currentColor = disabledColor ?? Theme.of(context).disabledColor;
280

281 282 283 284 285 286 287 288 289 290 291 292 293
    Widget result = ConstrainedBox(
      constraints: const BoxConstraints(minWidth: _kMinButtonSize, minHeight: _kMinButtonSize),
      child: Padding(
        padding: padding,
        child: SizedBox(
          height: iconSize,
          width: iconSize,
          child: Align(
            alignment: alignment,
            child: IconTheme.merge(
              data: IconThemeData(
                size: iconSize,
                color: currentColor,
294
              ),
295
              child: icon,
296 297 298 299
            ),
          ),
        ),
      ),
300
    );
301

Hixie's avatar
Hixie committed
302
    if (tooltip != null) {
303
      result = Tooltip(
Hixie's avatar
Hixie committed
304
        message: tooltip,
305
        child: result,
Hixie's avatar
Hixie committed
306 307
      );
    }
308 309 310 311

    return Semantics(
      button: true,
      enabled: onPressed != null,
312
      child: InkResponse(
313
        focusNode: focusNode,
314
        autofocus: autofocus,
315
        canRequestFocus: onPressed != null,
316 317 318 319 320 321 322 323 324 325
        onTap: onPressed,
        child: result,
        focusColor: focusColor ?? Theme.of(context).focusColor,
        hoverColor: hoverColor ?? Theme.of(context).hoverColor,
        highlightColor: highlightColor ?? Theme.of(context).highlightColor,
        splashColor: splashColor ?? Theme.of(context).splashColor,
        radius: math.max(
          Material.defaultSplashRadius,
          (iconSize + math.min(padding.horizontal, padding.vertical)) * 0.7,
          // x 0.5 for diameter -> radius and + 40% overflow derived from other Material apps.
326
        ),
327
      ),
Hixie's avatar
Hixie committed
328
    );
329
  }
Hixie's avatar
Hixie committed
330

331
  @override
332 333
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
334 335
    properties.add(DiagnosticsProperty<Widget>('icon', icon, showName: false));
    properties.add(StringProperty('tooltip', tooltip, defaultValue: null, quoted: false));
336
    properties.add(ObjectFlagProperty<VoidCallback>('onPressed', onPressed, ifNull: 'disabled'));
337 338 339 340 341 342
    properties.add(ColorProperty('color', color, defaultValue: null));
    properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: null));
    properties.add(ColorProperty('focusColor', focusColor, defaultValue: null));
    properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null));
    properties.add(ColorProperty('highlightColor', highlightColor, defaultValue: null));
    properties.add(ColorProperty('splashColor', splashColor, defaultValue: null));
343 344
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
Hixie's avatar
Hixie committed
345
  }
346
}