icon_button.dart 14.4 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/rendering.dart';
9
import 'package:flutter/widgets.dart';
10

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

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

24
/// A material design icon button.
25 26
///
/// An icon button is a picture printed on a [Material] widget that reacts to
27
/// touches by filling with color (ink).
28
///
29 30
/// Icon buttons are commonly used in the [AppBar.actions] field, but they can
/// be used in many other places as well.
31
///
32 33
/// If the [onPressed] callback is null, then the button will be disabled and
/// will not react to touch.
34
///
35 36
/// Requires one of its ancestors to be a [Material] widget.
///
37 38
/// The hit region of an icon button will, if possible, be at least
/// kMinInteractiveDimension pixels in size, regardless of the actual
39
/// [iconSize], to satisfy the [touch target size](https://material.io/design/layout/spacing-methods.html#touch-targets)
40 41
/// requirements in the Material Design specification. The [alignment] controls
/// how the icon itself is positioned within the hit region.
42
///
43
/// {@tool dartpad --template=stateful_widget_scaffold_center}
44 45 46 47
///
/// This sample shows an `IconButton` that uses the Material icon "volume_up" to
/// increase the volume.
///
48 49
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/icon_button.png)
///
50 51 52
/// ```dart preamble
/// double _volume = 0.0;
/// ```
53 54
///
/// ```dart
55
/// @override
56
/// Widget build(BuildContext context) {
57 58 59 60
///   return Column(
///     mainAxisSize: MainAxisSize.min,
///     children: <Widget>[
///       IconButton(
61
///         icon: const Icon(Icons.volume_up),
62 63 64 65 66 67
///         tooltip: 'Increase volume by 10',
///         onPressed: () {
///           setState(() {
///             _volume += 10;
///           });
///         },
68
///       ),
69 70
///       Text('Volume : $_volume')
///     ],
71 72
///   );
/// }
73
/// ```
74
/// {@end-tool}
75
///
76 77 78 79 80 81 82 83 84 85 86 87
/// ### 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.
///
88
/// {@tool dartpad --template=stateless_widget_scaffold}
89 90 91 92 93 94
///
/// 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.
///
95 96
/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/icon_button_background.png)
///
97
/// ```dart
98
/// @override
99
/// Widget build(BuildContext context) {
100 101 102
///   return Material(
///     color: Colors.white,
///     child: Center(
103
///       child: Ink(
104
///         decoration: const ShapeDecoration(
105 106 107 108
///           color: Colors.lightBlue,
///           shape: CircleBorder(),
///         ),
///         child: IconButton(
109
///           icon: const Icon(Icons.android),
110
///           color: Colors.white,
111
///           onPressed: () {},
112 113 114 115 116
///         ),
///       ),
///     ),
///   );
/// }
117 118 119
/// ```
/// {@end-tool}
///
120 121
/// See also:
///
122 123 124 125 126
///  * [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.
127
///  * [TextButton], [ElevatedButton], [OutlinedButton], for buttons with text labels and an optional icon.
128
///  * [InkResponse] and [InkWell], for the ink splash effect itself.
129
class IconButton extends StatelessWidget {
130 131 132 133 134 135
  /// 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.
136
  ///
137 138
  /// The [iconSize], [padding], [autofocus], and [alignment] arguments must not
  /// be null (though they each have default values).
139
  ///
Ian Hickson's avatar
Ian Hickson committed
140 141
  /// The [icon] argument must be specified, and is typically either an [Icon]
  /// or an [ImageIcon].
142
  const IconButton({
143
    Key? key,
144
    this.iconSize = 24.0,
145
    this.visualDensity,
146 147
    this.padding = const EdgeInsets.all(8.0),
    this.alignment = Alignment.center,
148
    this.splashRadius,
149
    this.color,
150 151
    this.focusColor,
    this.hoverColor,
152 153
    this.highlightColor,
    this.splashColor,
154
    this.disabledColor,
155
    required this.onPressed,
156
    this.mouseCursor = SystemMouseCursors.click,
157
    this.focusNode,
158
    this.autofocus = false,
159
    this.tooltip,
160
    this.enableFeedback = true,
161
    this.constraints,
162
    required this.icon,
163 164 165
  }) : assert(iconSize != null),
       assert(padding != null),
       assert(alignment != null),
166
       assert(splashRadius == null || splashRadius > 0),
167
       assert(autofocus != null),
168 169
       assert(icon != null),
       super(key: key);
170

Adam Barth's avatar
Adam Barth committed
171
  /// The size of the icon inside the button.
172 173
  ///
  /// This property must not be null. It defaults to 24.0.
174 175 176 177 178 179 180
  ///
  /// 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.
181
  final double iconSize;
Adam Barth's avatar
Adam Barth committed
182

183 184 185 186 187 188
  /// Defines how compact the icon button's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
189 190
  ///  * [ThemeData.visualDensity], which specifies the [visualDensity] for all
  ///    widgets within a [Theme].
191
  final VisualDensity? visualDensity;
192

193 194
  /// The padding around the button's icon. The entire padded icon will react
  /// to input gestures.
195 196
  ///
  /// This property must not be null. It defaults to 8.0 padding on all sides.
197
  final EdgeInsetsGeometry padding;
198 199

  /// Defines how the icon is positioned within the IconButton.
200
  ///
201
  /// This property must not be null. It defaults to [Alignment.center].
202 203 204 205 206 207 208
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
209
  final AlignmentGeometry alignment;
210

211 212 213
  /// The splash radius.
  ///
  /// If null, default splash radius of [Material.defaultSplashRadius] is used.
214
  final double? splashRadius;
215

Ian Hickson's avatar
Ian Hickson committed
216 217
  /// The icon to display inside the button.
  ///
218
  /// The [Icon.size] and [Icon.color] of the icon is configured automatically
219
  /// based on the [iconSize] and [color] properties of _this_ widget using an
220 221
  /// [IconTheme] and therefore should not be explicitly given in the icon
  /// widget.
222 223
  ///
  /// This property must not be null.
Ian Hickson's avatar
Ian Hickson committed
224 225 226
  ///
  /// See [Icon], [ImageIcon].
  final Widget icon;
Adam Barth's avatar
Adam Barth committed
227

228 229 230
  /// The color for the button's icon when it has the input focus.
  ///
  /// Defaults to [ThemeData.focusColor] of the ambient theme.
231
  final Color? focusColor;
232 233 234 235

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

238
  /// The color to use for the icon inside the button, if the icon is enabled.
Ian Hickson's avatar
Ian Hickson committed
239
  /// Defaults to leaving this up to the [icon] widget.
240 241 242
  ///
  /// The icon is enabled if [onPressed] is not null.
  ///
243
  /// ```dart
244 245 246 247
  /// IconButton(
  ///   color: Colors.blue,
  ///   onPressed: _handleTap,
  ///   icon: Icons.widgets,
248
  /// )
249
  /// ```
250
  final Color? color;
251

252 253 254 255 256 257 258 259
  /// 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].
260
  final Color? splashColor;
261 262

  /// The secondary color of the button when the button is in the down (pressed)
263
  /// state. The highlight color is represented as a solid color that is overlaid over the
264 265 266 267
  /// 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].
268
  final Color? highlightColor;
269

270 271 272 273
  /// 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.
274
  final Color? disabledColor;
275

276
  /// The callback that is called when the button is tapped or otherwise activated.
277 278
  ///
  /// If this is set to null, the button will be disabled.
279
  final VoidCallback? onPressed;
Adam Barth's avatar
Adam Barth committed
280

281
  /// {@macro flutter.material.RawMaterialButton.mouseCursor}
282 283 284 285
  ///
  /// Defaults to [SystemMouseCursors.click].
  final MouseCursor mouseCursor;

286
  /// {@macro flutter.widgets.Focus.focusNode}
287
  final FocusNode? focusNode;
288

289 290 291
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

Adam Barth's avatar
Adam Barth committed
292 293 294 295
  /// 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.
296
  final String? tooltip;
297

298 299 300 301 302 303 304 305 306 307
  /// 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;

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  /// Optional size constraints for the button.
  ///
  /// When unspecified, defaults to:
  /// ```dart
  /// const BoxConstraints(
  ///   minWidth: kMinInteractiveDimension,
  ///   minHeight: kMinInteractiveDimension,
  /// )
  /// ```
  /// where [kMinInteractiveDimension] is 48.0, and then with visual density
  /// applied.
  ///
  /// The default constraints ensure that the button is accessible.
  /// Specifying this parameter enables creation of buttons smaller than
  /// the minimum size, but it is not recommended.
  ///
  /// The visual density uses the [visualDensity] parameter if specified,
  /// and `Theme.of(context).visualDensity` otherwise.
326
  final BoxConstraints? constraints;
327

328
  @override
329
  Widget build(BuildContext context) {
330
    assert(debugCheckHasMaterial(context));
331
    final ThemeData theme = Theme.of(context);
332
    Color? currentColor;
333 334 335
    if (onPressed != null)
      currentColor = color;
    else
336
      currentColor = disabledColor ?? theme.disabledColor;
337

338 339 340 341 342 343 344 345
    final VisualDensity effectiveVisualDensity = visualDensity ?? theme.visualDensity;

    final BoxConstraints unadjustedConstraints = constraints ?? const BoxConstraints(
      minWidth: _kMinButtonSize,
      minHeight: _kMinButtonSize,
    );
    final BoxConstraints adjustedConstraints = effectiveVisualDensity.effectiveConstraints(unadjustedConstraints);

346
    Widget result = ConstrainedBox(
347
      constraints: adjustedConstraints,
348 349 350 351 352 353 354 355 356 357 358
      child: Padding(
        padding: padding,
        child: SizedBox(
          height: iconSize,
          width: iconSize,
          child: Align(
            alignment: alignment,
            child: IconTheme.merge(
              data: IconThemeData(
                size: iconSize,
                color: currentColor,
359
              ),
360
              child: icon,
361 362 363 364
            ),
          ),
        ),
      ),
365
    );
366

Hixie's avatar
Hixie committed
367
    if (tooltip != null) {
368
      result = Tooltip(
369
        message: tooltip!,
370
        child: result,
Hixie's avatar
Hixie committed
371 372
      );
    }
373 374 375 376

    return Semantics(
      button: true,
      enabled: onPressed != null,
377
      child: InkResponse(
378
        focusNode: focusNode,
379
        autofocus: autofocus,
380
        canRequestFocus: onPressed != null,
381
        onTap: onPressed,
382
        mouseCursor: mouseCursor,
383
        enableFeedback: enableFeedback,
384 385 386 387
        focusColor: focusColor ?? theme.focusColor,
        hoverColor: hoverColor ?? theme.hoverColor,
        highlightColor: highlightColor ?? theme.highlightColor,
        splashColor: splashColor ?? theme.splashColor,
388
        radius: splashRadius ?? math.max(
389 390 391
          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.
392
        ),
393
        child: result,
394
      ),
Hixie's avatar
Hixie committed
395
    );
396
  }
Hixie's avatar
Hixie committed
397

398
  @override
399 400
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
401 402
    properties.add(DiagnosticsProperty<Widget>('icon', icon, showName: false));
    properties.add(StringProperty('tooltip', tooltip, defaultValue: null, quoted: false));
403
    properties.add(ObjectFlagProperty<VoidCallback>('onPressed', onPressed, ifNull: 'disabled'));
404 405 406 407 408 409
    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));
410 411
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
Hixie's avatar
Hixie committed
412
  }
413
}