radio.dart 9.66 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
import 'package:flutter/rendering.dart';
6
import 'package:flutter/widgets.dart';
7

8
import 'constants.dart';
9
import 'debug.dart';
10
import 'theme.dart';
11
import 'theme_data.dart';
12
import 'toggleable.dart';
13

14 15
const double _kOuterRadius = 8.0;
const double _kInnerRadius = 4.5;
16

17 18
/// A material design radio button.
///
19 20 21 22
/// Used to select between a number of mutually exclusive values. When one radio
/// button in a group is selected, the other radio buttons in the group cease to
/// be selected. The values are of type `T`, the type parameter of the [Radio]
/// class. Enums are commonly used for this purpose.
23
///
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/// The radio button itself does not maintain any state. Instead, selecting the
/// radio invokes the [onChanged] callback, passing [value] as a parameter. If
/// [groupValue] and [value] match, this radio will be selected. Most widgets
/// will respond to [onChanged] by calling [State.setState] to update the
/// radio button's [groupValue].
///
/// {@tool snippet --template=stateful_widget_scaffold}
///
/// Here is an example of Radio widgets wrapped in ListTiles, which is similar
/// to what you could get with the RadioListTile widget.
///
/// The currently selected character is passed into `groupValue`, which is
/// maintained by the example's `State`. In this case, the first `Radio`
/// will start off selected because `_character` is initialized to
/// `SingingCharacter.lafayette`.
///
/// If the second radio button is pressed, the example's state is updated
/// with `setState`, updating `_character` to `SingingCharacter.jefferson`.
/// This causes the buttons to rebuild with the updated `groupValue`, and
/// therefore the selection of the second button.
///
45 46
/// Requires one of its ancestors to be a [Material] widget.
///
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/// ```dart preamble
/// enum SingingCharacter { lafayette, jefferson }
/// ```
///
/// ```dart
/// SingingCharacter _character = SingingCharacter.lafayette;
///
/// Widget build(BuildContext context) {
///   return Center(
///     child: Column(
///       children: <Widget>[
///         ListTile(
///           title: const Text('Lafayette'),
///           leading: Radio(
///             value: SingingCharacter.lafayette,
///             groupValue: _character,
///             onChanged: (SingingCharacter value) {
///               setState(() { _character = value; });
///             },
///           ),
///         ),
///         ListTile(
///           title: const Text('Thomas Jefferson'),
///           leading: Radio(
///             value: SingingCharacter.jefferson,
///             groupValue: _character,
///             onChanged: (SingingCharacter value) {
///               setState(() { _character = value; });
///             },
///           ),
///         ),
///       ],
///     ),
///   );
/// }
/// ```
/// {@end-tool}
84 85
///
/// See also:
86
///
87 88
///  * [RadioListTile], which combines this widget with a [ListTile] so that
///    you can give the radio button a label.
89 90
///  * [Slider], for selecting a value in a range.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
91
///  * <https://material.io/design/components/selection-controls.html#radio-buttons>
92
class Radio<T> extends StatefulWidget {
93 94
  /// Creates a material design radio button.
  ///
95 96 97 98 99
  /// The radio button itself does not maintain any state. Instead, when the
  /// radio button is selected, the widget calls the [onChanged] callback. Most
  /// widgets that use a radio button will listen for the [onChanged] callback
  /// and rebuild the radio button with a new [groupValue] to update the visual
  /// appearance of the radio button.
100
  ///
101 102 103 104 105
  /// The following arguments are required:
  ///
  /// * [value] and [groupValue] together determine whether the radio button is
  ///   selected.
  /// * [onChanged] is called when the user selects this radio button.
106
  const Radio({
107
    Key key,
108 109 110
    @required this.value,
    @required this.groupValue,
    @required this.onChanged,
111 112
    this.activeColor,
    this.materialTapTargetSize,
113
  }) : super(key: key);
114

115
  /// The value represented by this radio button.
Hixie's avatar
Hixie committed
116
  final T value;
117

118
  /// The currently selected value for a group of radio buttons.
119 120 121
  ///
  /// This radio button is considered selected if its [value] matches the
  /// [groupValue].
Hixie's avatar
Hixie committed
122
  final T groupValue;
123 124 125

  /// Called when the user selects this radio button.
  ///
126 127 128 129 130
  /// The radio button passes [value] as a parameter to this callback. The radio
  /// button does not actually change state until the parent widget rebuilds the
  /// radio button with the new [groupValue].
  ///
  /// If null, the radio button will be displayed as disabled.
131
  ///
132 133 134
  /// The provided callback will not be invoked if this radio button is already
  /// selected.
  ///
135
  /// The callback provided to [onChanged] should update the state of the parent
136 137 138 139
  /// [StatefulWidget] using the [State.setState] method, so that the parent
  /// gets rebuilt; for example:
  ///
  /// ```dart
140
  /// Radio<SingingCharacter>(
141 142 143 144 145 146 147
  ///   value: SingingCharacter.lafayette,
  ///   groupValue: _character,
  ///   onChanged: (SingingCharacter newValue) {
  ///     setState(() {
  ///       _character = newValue;
  ///     });
  ///   },
148
  /// )
149
  /// ```
Hixie's avatar
Hixie committed
150
  final ValueChanged<T> onChanged;
151

152 153
  /// The color to use when this radio button is selected.
  ///
154
  /// Defaults to [ThemeData.toggleableActiveColor].
155 156
  final Color activeColor;

157 158 159 160 161 162
  /// Configures the minimum size of the tap target.
  ///
  /// Defaults to [ThemeData.materialTapTargetSize].
  ///
  /// See also:
  ///
163
  ///  * [MaterialTapTargetSize], for a description of how this affects tap targets.
164 165
  final MaterialTapTargetSize materialTapTargetSize;

166
  @override
167
  _RadioState<T> createState() => _RadioState<T>();
168 169 170
}

class _RadioState<T> extends State<Radio<T>> with TickerProviderStateMixin {
171
  bool get _enabled => widget.onChanged != null;
172

173
  Color _getInactiveColor(ThemeData themeData) {
174
    return _enabled ? themeData.unselectedWidgetColor : themeData.disabledColor;
175 176
  }

177 178
  void _handleChanged(bool selected) {
    if (selected)
179
      widget.onChanged(widget.value);
180 181
  }

182
  @override
183
  Widget build(BuildContext context) {
184
    assert(debugCheckHasMaterial(context));
185
    final ThemeData themeData = Theme.of(context);
186 187 188 189 190 191 192 193 194
    Size size;
    switch (widget.materialTapTargetSize ?? themeData.materialTapTargetSize) {
      case MaterialTapTargetSize.padded:
        size = const Size(2 * kRadialReactionRadius + 8.0, 2 * kRadialReactionRadius + 8.0);
        break;
      case MaterialTapTargetSize.shrinkWrap:
        size = const Size(2 * kRadialReactionRadius, 2 * kRadialReactionRadius);
        break;
    }
195 196
    final BoxConstraints additionalConstraints = BoxConstraints.tight(size);
    return _RadioRenderObjectWidget(
197
      selected: widget.value == widget.groupValue,
198
      activeColor: widget.activeColor ?? themeData.toggleableActiveColor,
199 200
      inactiveColor: _getInactiveColor(themeData),
      onChanged: _enabled ? _handleChanged : null,
201
      additionalConstraints: additionalConstraints,
202
      vsync: this,
203 204 205
    );
  }
}
206 207

class _RadioRenderObjectWidget extends LeafRenderObjectWidget {
208
  const _RadioRenderObjectWidget({
209
    Key key,
210 211 212
    @required this.selected,
    @required this.activeColor,
    @required this.inactiveColor,
213
    @required this.additionalConstraints,
214 215
    this.onChanged,
    @required this.vsync,
216 217 218 219 220
  }) : assert(selected != null),
       assert(activeColor != null),
       assert(inactiveColor != null),
       assert(vsync != null),
       super(key: key);
221 222 223

  final bool selected;
  final Color inactiveColor;
224
  final Color activeColor;
225
  final ValueChanged<bool> onChanged;
226
  final TickerProvider vsync;
227
  final BoxConstraints additionalConstraints;
228

229
  @override
230
  _RenderRadio createRenderObject(BuildContext context) => _RenderRadio(
231
    value: selected,
232
    activeColor: activeColor,
233
    inactiveColor: inactiveColor,
234 235
    onChanged: onChanged,
    vsync: vsync,
236
    additionalConstraints: additionalConstraints,
237 238
  );

239
  @override
240
  void updateRenderObject(BuildContext context, _RenderRadio renderObject) {
241 242 243 244
    renderObject
      ..value = selected
      ..activeColor = activeColor
      ..inactiveColor = inactiveColor
245
      ..onChanged = onChanged
246
      ..additionalConstraints = additionalConstraints
247
      ..vsync = vsync;
248 249 250 251 252 253
  }
}

class _RenderRadio extends RenderToggleable {
  _RenderRadio({
    bool value,
254
    Color activeColor,
255
    Color inactiveColor,
256
    ValueChanged<bool> onChanged,
257
    BoxConstraints additionalConstraints,
258
    @required TickerProvider vsync,
259 260 261 262 263 264 265 266 267
  }) : super(
         value: value,
         tristate: false,
         activeColor: activeColor,
         inactiveColor: inactiveColor,
         onChanged: onChanged,
         additionalConstraints: additionalConstraints,
         vsync: vsync,
       );
268

269
  @override
270 271 272
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;

273
    paintRadialReaction(canvas, offset, size.center(Offset.zero));
274

275
    final Offset center = (offset & size).center;
276
    final Color radioColor = onChanged != null ? activeColor : inactiveColor;
277 278

    // Outer circle
279
    final Paint paint = Paint()
280
      ..color = Color.lerp(inactiveColor, radioColor, position.value)
281
      ..style = PaintingStyle.stroke
282 283 284 285 286
      ..strokeWidth = 2.0;
    canvas.drawCircle(center, _kOuterRadius, paint);

    // Inner circle
    if (!position.isDismissed) {
287
      paint.style = PaintingStyle.fill;
288 289 290
      canvas.drawCircle(center, _kInnerRadius * position.value, paint);
    }
  }
291 292 293 294

  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
295 296 297
    config
      ..isInMutuallyExclusiveGroup = true
      ..isChecked = value == true;
298
  }
299
}