choice_chip.dart 10.2 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter 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
import 'package:flutter/foundation.dart' show clampDouble;
6 7 8 9
import 'package:flutter/widgets.dart';

import 'chip.dart';
import 'chip_theme.dart';
10
import 'color_scheme.dart';
11
import 'colors.dart';
12
import 'debug.dart';
13
import 'material_state.dart';
14
import 'text_theme.dart';
15
import 'theme.dart';
16 17
import 'theme_data.dart';

18 19
enum _ChipVariant { flat, elevated }

20
/// A Material Design choice chip.
21 22 23 24
///
/// [ChoiceChip]s represent a single choice from a set. Choice chips contain
/// related descriptive text or categories.
///
25
/// Requires one of its ancestors to be a [Material] widget.
26
///
27 28 29
/// {@tool dartpad}
/// This example shows how to create [ChoiceChip]s with [onSelected]. When the
/// user taps, the chip will be selected.
30
///
31
/// ** See code in examples/api/lib/material/choice_chip/choice_chip.0.dart **
32 33
/// {@end-tool}
///
34 35 36 37 38 39 40
/// ## Material Design 3
///
/// [ChoiceChip] can be used for single select Filter chips from
/// Material Design 3. If [ThemeData.useMaterial3] is true, then [ChoiceChip]
/// will be styled to match the Material Design 3 specification for Filter
/// chips. Use [FilterChip] for multiple select Filter chips.
///
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/// See also:
///
///  * [Chip], a chip that displays information and can be deleted.
///  * [InputChip], a chip that represents a complex piece of information, such
///    as an entity (person, place, or thing) or conversational text, in a
///    compact form.
///  * [FilterChip], uses tags or descriptive words as a way to filter content.
///  * [ActionChip], represents an action related to primary content.
///  * [CircleAvatar], which shows images or initials of people.
///  * [Wrap], A widget that displays its children in multiple horizontal or
///    vertical runs.
///  * <https://material.io/design/components/chips.html>
class ChoiceChip extends StatelessWidget
    implements
        ChipAttributes,
        SelectableChipAttributes,
57
        CheckmarkableChipAttributes,
58 59 60 61 62 63 64
        DisabledChipAttributes {
  /// Create a chip that acts like a radio button.
  ///
  /// The [label], [selected], [autofocus], and [clipBehavior] arguments must
  /// not be null. The [pressElevation] and [elevation] must be null or
  /// non-negative. Typically, [pressElevation] is greater than [elevation].
  const ChoiceChip({
65
    super.key,
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    this.avatar,
    required this.label,
    this.labelStyle,
    this.labelPadding,
    this.onSelected,
    this.pressElevation,
    required this.selected,
    this.selectedColor,
    this.disabledColor,
    this.tooltip,
    this.side,
    this.shape,
    this.clipBehavior = Clip.none,
    this.focusNode,
    this.autofocus = false,
81
    this.color,
82 83 84 85 86 87
    this.backgroundColor,
    this.padding,
    this.visualDensity,
    this.materialTapTargetSize,
    this.elevation,
    this.shadowColor,
88 89
    this.surfaceTintColor,
    this.iconTheme,
90
    this.selectedShadowColor,
91 92
    this.showCheckmark,
    this.checkmarkColor,
93
    this.avatarBorder = const CircleBorder(),
94
  }) : assert(pressElevation == null || pressElevation >= 0.0),
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
       assert(elevation == null || elevation >= 0.0),
       _chipVariant = _ChipVariant.flat;

  /// Create an elevated chip that acts like a radio button.
  ///
  /// The [label], [selected], [autofocus], and [clipBehavior] arguments must
  /// not be null. The [pressElevation] and [elevation] must be null or
  /// non-negative. Typically, [pressElevation] is greater than [elevation].
  const ChoiceChip.elevated({
    super.key,
    this.avatar,
    required this.label,
    this.labelStyle,
    this.labelPadding,
    this.onSelected,
    this.pressElevation,
    required this.selected,
    this.selectedColor,
    this.disabledColor,
    this.tooltip,
    this.side,
    this.shape,
    this.clipBehavior = Clip.none,
    this.focusNode,
    this.autofocus = false,
120
    this.color,
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    this.backgroundColor,
    this.padding,
    this.visualDensity,
    this.materialTapTargetSize,
    this.elevation,
    this.shadowColor,
    this.surfaceTintColor,
    this.iconTheme,
    this.selectedShadowColor,
    this.showCheckmark,
    this.checkmarkColor,
    this.avatarBorder = const CircleBorder(),
  }) : assert(pressElevation == null || pressElevation >= 0.0),
       assert(elevation == null || elevation >= 0.0),
       _chipVariant = _ChipVariant.elevated;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

  @override
  final Widget? avatar;
  @override
  final Widget label;
  @override
  final TextStyle? labelStyle;
  @override
  final EdgeInsetsGeometry? labelPadding;
  @override
  final ValueChanged<bool>? onSelected;
  @override
  final double? pressElevation;
  @override
  final bool selected;
  @override
  final Color? disabledColor;
  @override
  final Color? selectedColor;
  @override
  final String? tooltip;
  @override
  final BorderSide? side;
  @override
  final OutlinedBorder? shape;
  @override
  final Clip clipBehavior;
  @override
  final FocusNode? focusNode;
  @override
  final bool autofocus;
  @override
168 169
  final MaterialStateProperty<Color?>? color;
  @override
170 171 172 173 174 175 176 177 178 179 180 181
  final Color? backgroundColor;
  @override
  final EdgeInsetsGeometry? padding;
  @override
  final VisualDensity? visualDensity;
  @override
  final MaterialTapTargetSize? materialTapTargetSize;
  @override
  final double? elevation;
  @override
  final Color? shadowColor;
  @override
182 183
  final Color? surfaceTintColor;
  @override
184 185
  final Color? selectedShadowColor;
  @override
186 187 188 189
  final bool? showCheckmark;
  @override
  final Color? checkmarkColor;
  @override
190
  final ShapeBorder avatarBorder;
191 192
  @override
  final IconThemeData? iconTheme;
193 194 195 196

  @override
  bool get isEnabled => onSelected != null;

197 198
  final _ChipVariant _chipVariant;

199 200 201 202
  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
    final ChipThemeData chipTheme = ChipTheme.of(context);
203
    final ChipThemeData? defaults = Theme.of(context).useMaterial3
204
      ? _ChoiceChipDefaultsM3(context, isEnabled, selected, _chipVariant)
205
      : null;
206
    return RawChip(
207
      defaultProperties: defaults,
208 209 210 211 212 213 214
      avatar: avatar,
      label: label,
      labelStyle: labelStyle ?? (selected ? chipTheme.secondaryLabelStyle : null),
      labelPadding: labelPadding,
      onSelected: onSelected,
      pressElevation: pressElevation,
      selected: selected,
215 216
      showCheckmark: showCheckmark ?? chipTheme.showCheckmark ?? Theme.of(context).useMaterial3,
      checkmarkColor: checkmarkColor,
217 218 219 220 221 222 223 224
      tooltip: tooltip,
      side: side,
      shape: shape,
      clipBehavior: clipBehavior,
      focusNode: focusNode,
      autofocus: autofocus,
      disabledColor: disabledColor,
      selectedColor: selectedColor ?? chipTheme.secondarySelectedColor,
225
      color: color,
226 227 228 229 230 231 232
      backgroundColor: backgroundColor,
      padding: padding,
      visualDensity: visualDensity,
      isEnabled: isEnabled,
      materialTapTargetSize: materialTapTargetSize,
      elevation: elevation,
      shadowColor: shadowColor,
233
      surfaceTintColor: surfaceTintColor,
234 235
      selectedShadowColor: selectedShadowColor,
      avatarBorder: avatarBorder,
236
      iconTheme: iconTheme,
237 238 239
    );
  }
}
240

241
// BEGIN GENERATED TOKEN PROPERTIES - ChoiceChip
242

243 244 245 246
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
//   dev/tools/gen_defaults/bin/gen_defaults.dart.
247

248
class _ChoiceChipDefaultsM3 extends ChipThemeData {
249 250 251 252 253 254
  _ChoiceChipDefaultsM3(
    this.context,
    this.isEnabled,
    this.isSelected,
    this._chipVariant,
  ) : super(
255
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
256 257 258 259 260 261
        showCheckmark: true,
      );

  final BuildContext context;
  final bool isEnabled;
  final bool isSelected;
262
  final _ChipVariant _chipVariant;
263 264
  late final ColorScheme _colors = Theme.of(context).colorScheme;
  late final TextTheme _textTheme = Theme.of(context).textTheme;
265

266 267 268 269 270 271 272 273
  @override
  double? get elevation => _chipVariant == _ChipVariant.flat
    ? 0.0
    : isEnabled ? 1.0 : 0.0;

  @override
  double? get pressElevation => 1.0;

274
  @override
275
  TextStyle? get labelStyle => _textTheme.labelLarge;
276 277

  @override
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  MaterialStateProperty<Color?>? get color =>
    MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.selected) && states.contains(MaterialState.disabled)) {
        return _chipVariant == _ChipVariant.flat
          ? _colors.onSurface.withOpacity(0.12)
          : _colors.onSurface.withOpacity(0.12);
      }
      if (states.contains(MaterialState.disabled)) {
        return _chipVariant == _ChipVariant.flat
          ? null
          : _colors.onSurface.withOpacity(0.12);
      }
      if (states.contains(MaterialState.selected)) {
        return _chipVariant == _ChipVariant.flat
          ? _colors.secondaryContainer
          : _colors.secondaryContainer;
      }
      return _chipVariant == _ChipVariant.flat
        ? null
        : null;
    });
299 300

  @override
301 302 303
  Color? get shadowColor => _chipVariant == _ChipVariant.flat
    ? Colors.transparent
    : _colors.shadow;
304 305

  @override
306
  Color? get surfaceTintColor => _colors.surfaceTint;
307 308

  @override
309
  Color? get checkmarkColor => _colors.onSecondaryContainer;
310 311

  @override
312
  Color? get deleteIconColor => _colors.onSecondaryContainer;
313 314

  @override
315
  BorderSide? get side => _chipVariant == _ChipVariant.flat && !isSelected
316
    ? isEnabled
317 318
      ? BorderSide(color: _colors.outline)
      : BorderSide(color: _colors.onSurface.withOpacity(0.12))
319
    : const BorderSide(color: Colors.transparent);
320 321 322 323 324

  @override
  IconThemeData? get iconTheme => IconThemeData(
    color: isEnabled
      ? null
325
      : _colors.onSurface,
326 327 328 329 330 331 332 333 334 335 336 337 338 339
    size: 18.0,
  );

  @override
  EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0);

  /// The chip at text scale 1 starts with 8px on each side and as text scaling
  /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px.
  /// Once the widget has a text scaling of 2 or higher than the label padding
  /// remains 4px.
  @override
  EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
    const EdgeInsets.symmetric(horizontal: 8.0),
    const EdgeInsets.symmetric(horizontal: 4.0),
340
    clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0),
341 342 343
  )!;
}

344
// END GENERATED TOKEN PROPERTIES - ChoiceChip