picker.dart 18.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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/rendering.dart';
7
import 'package:flutter/services.dart';
8 9
import 'package:flutter/widgets.dart';

10
import 'colors.dart';
11 12 13 14 15 16 17
import 'theme.dart';

// Eyeballed values comparing with a native picker to produce the right
// curvatures and densities.
const double _kDefaultDiameterRatio = 1.07;
const double _kDefaultPerspective = 0.003;
const double _kSqueeze = 1.45;
18 19 20 21

// Opacity fraction value that dims the wheel above and below the "magnifier"
// lens.
const double _kOverAndUnderCenterOpacity = 0.447;
22 23 24

/// An iOS-styled picker.
///
25
/// Displays its children widgets on a wheel for selection and
26 27
/// calls back when the currently selected item changes.
///
Dan Field's avatar
Dan Field committed
28
/// By default, the first child in `children` will be the initially selected child.
29 30 31
/// The index of a different child can be specified in [scrollController], to make
/// that child the initially selected child.
///
32
/// Can be used with [showCupertinoModalPopup] to display the picker modally at the
Dan Field's avatar
Dan Field committed
33 34
/// bottom of the screen. When calling [showCupertinoModalPopup], be sure to set
/// `semanticsDismissible` to true to enable dismissing the modal via semantics.
35
///
36 37 38 39 40
/// Sizes itself to its parent. All children are sized to the same size based
/// on [itemExtent].
///
/// By default, descendent texts are shown with [CupertinoTextThemeData.pickerTextStyle].
///
41 42 43 44 45 46 47
/// {@tool dartpad}
/// This example shows a [CupertinoPicker] that displays a list of fruits on a wheel for
/// selection.
///
/// ** See code in examples/api/lib/cupertino/picker/cupertino_picker.0.dart **
/// {@end-tool}
///
48 49 50 51 52 53
/// See also:
///
///  * [ListWheelScrollView], the generic widget backing this picker without
///    the iOS design specific chrome.
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/pickers/>
class CupertinoPicker extends StatefulWidget {
54
  /// Creates a picker from a concrete list of children.
55 56 57 58
  ///
  /// The [diameterRatio] and [itemExtent] arguments must not be null. The
  /// [itemExtent] must be greater than zero.
  ///
59 60 61
  /// The [backgroundColor] defaults to null, which disables background painting entirely.
  /// (i.e. the picker is going to have a completely transparent background), to match
  /// the native UIPicker and UIDatePicker. Also, if it has transparency, no gradient
62
  /// effect will be rendered.
63
  ///
64 65 66 67
  /// The [scrollController] argument can be used to specify a custom
  /// [FixedExtentScrollController] for programmatically reading or changing
  /// the current picker index or for selecting an initial index value.
  ///
68
  /// The [looping] argument decides whether the child list loops and can be
69 70
  /// scrolled infinitely. If set to true, scrolling past the end of the list
  /// will loop the list back to the beginning. If set to false, the list will
71 72
  /// stop scrolling when you reach the end or the beginning.
  CupertinoPicker({
73
    super.key,
74
    this.diameterRatio = _kDefaultDiameterRatio,
75
    this.backgroundColor,
76 77 78 79
    this.offAxisFraction = 0.0,
    this.useMagnifier = false,
    this.magnification = 1.0,
    this.scrollController,
80
    this.squeeze = _kSqueeze,
81 82 83
    required this.itemExtent,
    required this.onSelectedItemChanged,
    required List<Widget> children,
84
    this.selectionOverlay = const CupertinoPickerDefaultSelectionOverlay(),
85
    bool looping = false,
86
  }) : assert(diameterRatio > 0.0, RenderListWheelViewport.diameterRatioZeroMessage),
87 88
       assert(magnification > 0),
       assert(itemExtent > 0),
89
       assert(squeeze > 0),
90
       childDelegate = looping
91
                       ? ListWheelChildLoopingListDelegate(children: children)
92
                       : ListWheelChildListDelegate(children: children);
93 94 95 96 97 98 99 100 101 102 103

  /// Creates a picker from an [IndexedWidgetBuilder] callback where the builder
  /// is dynamically invoked during layout.
  ///
  /// A child is lazily created when it starts becoming visible in the viewport.
  /// All of the children provided by the builder are cached and reused, so
  /// normally the builder is only called once for each index (except when
  /// rebuilding - the cache is cleared).
  ///
  /// The [itemBuilder] argument must not be null. The [childCount] argument
  /// reflects the number of children that will be provided by the [itemBuilder].
104
  /// {@macro flutter.widgets.ListWheelChildBuilderDelegate.childCount}
105 106 107
  ///
  /// The [itemExtent] argument must be non-null and positive.
  ///
108 109 110
  /// The [backgroundColor] defaults to null, which disables background painting entirely.
  /// (i.e. the picker is going to have a completely transparent background), to match
  /// the native UIPicker and UIDatePicker.
111
  CupertinoPicker.builder({
112
    super.key,
113
    this.diameterRatio = _kDefaultDiameterRatio,
114
    this.backgroundColor,
115 116 117
    this.offAxisFraction = 0.0,
    this.useMagnifier = false,
    this.magnification = 1.0,
118
    this.scrollController,
119
    this.squeeze = _kSqueeze,
120 121 122 123
    required this.itemExtent,
    required this.onSelectedItemChanged,
    required NullableIndexedWidgetBuilder itemBuilder,
    int? childCount,
124
    this.selectionOverlay = const CupertinoPickerDefaultSelectionOverlay(),
125
  }) : assert(diameterRatio > 0.0, RenderListWheelViewport.diameterRatioZeroMessage),
126
       assert(magnification > 0),
127
       assert(itemExtent > 0),
128
       assert(squeeze > 0),
129
       childDelegate = ListWheelChildBuilderDelegate(builder: itemBuilder, childCount: childCount);
130 131 132 133 134 135 136 137 138 139 140 141

  /// Relative ratio between this picker's height and the simulated cylinder's diameter.
  ///
  /// Smaller values creates more pronounced curvatures in the scrollable wheel.
  ///
  /// For more details, see [ListWheelScrollView.diameterRatio].
  ///
  /// Must not be null and defaults to `1.1` to visually mimic iOS.
  final double diameterRatio;

  /// Background color behind the children.
  ///
142 143 144
  /// Defaults to null, which disables background painting entirely.
  /// (i.e. the picker is going to have a completely transparent background), to match
  /// the native UIPicker and UIDatePicker.
145 146 147
  ///
  /// Any alpha value less 255 (fully opaque) will cause the removal of the
  /// wheel list edge fade gradient from rendering of the widget.
148
  final Color? backgroundColor;
149

150
  /// {@macro flutter.rendering.RenderListWheelViewport.offAxisFraction}
151 152
  final double offAxisFraction;

153
  /// {@macro flutter.rendering.RenderListWheelViewport.useMagnifier}
154 155
  final bool useMagnifier;

156
  /// {@macro flutter.rendering.RenderListWheelViewport.magnification}
157 158
  final double magnification;

159 160
  /// A [FixedExtentScrollController] to read and control the current item, and
  /// to set the initial item.
161 162
  ///
  /// If null, an implicit one will be created internally.
163
  final FixedExtentScrollController? scrollController;
164 165 166 167 168 169 170

  /// The uniform height of all children.
  ///
  /// All children will be given the [BoxConstraints] to match this exact
  /// height. Must not be null and must be positive.
  final double itemExtent;

171
  /// {@macro flutter.rendering.RenderListWheelViewport.squeeze}
172
  ///
173
  /// Defaults to `1.45` to visually mimic iOS.
174 175
  final double squeeze;

176 177 178 179 180 181 182
  /// An option callback when the currently centered item changes.
  ///
  /// Value changes when the item closest to the center changes.
  ///
  /// This can be called during scrolls and during ballistic flings. To get the
  /// value only when the scrolling settles, use a [NotificationListener],
  /// listen for [ScrollEndNotification] and read its [FixedExtentMetrics].
183
  final ValueChanged<int>? onSelectedItemChanged;
184

185 186
  /// A delegate that lazily instantiates children.
  final ListWheelChildDelegate childDelegate;
187

188 189 190 191 192 193 194 195 196 197
  /// A widget overlaid on the picker to highlight the currently selected entry.
  ///
  /// The [selectionOverlay] widget drawn above the [CupertinoPicker]'s picker
  /// wheel.
  /// It is vertically centered in the picker and is constrained to have the
  /// same height as the center row.
  ///
  /// If unspecified, it defaults to a [CupertinoPickerDefaultSelectionOverlay]
  /// which is a gray rounded rectangle overlay in iOS 14 style.
  /// This property can be set to null to remove the overlay.
198
  final Widget? selectionOverlay;
199

200
  @override
201
  State<StatefulWidget> createState() => _CupertinoPickerState();
202 203 204
}

class _CupertinoPickerState extends State<CupertinoPicker> {
205 206
  int? _lastHapticIndex;
  FixedExtentScrollController? _controller;
207 208 209 210 211 212 213 214 215 216 217

  @override
  void initState() {
    super.initState();
    if (widget.scrollController == null) {
      _controller = FixedExtentScrollController();
    }
  }

  @override
  void didUpdateWidget(CupertinoPicker oldWidget) {
218
    super.didUpdateWidget(oldWidget);
219 220 221 222 223 224 225 226 227 228 229 230 231
    if (widget.scrollController != null && oldWidget.scrollController == null) {
      _controller = null;
    } else if (widget.scrollController == null && oldWidget.scrollController != null) {
      assert(_controller == null);
      _controller = FixedExtentScrollController();
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }
232 233

  void _handleSelectedItemChanged(int index) {
234 235
    // Only the haptic engine hardware on iOS devices would produce the
    // intended effects.
236
    final bool hasSuitableHapticHardware;
237 238 239 240 241
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
        hasSuitableHapticHardware = true;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
242
      case TargetPlatform.linux:
243
      case TargetPlatform.macOS:
244
      case TargetPlatform.windows:
245 246 247
        hasSuitableHapticHardware = false;
    }
    if (hasSuitableHapticHardware && index != _lastHapticIndex) {
248
      _lastHapticIndex = index;
249
      HapticFeedback.selectionClick();
250 251
    }

252
    widget.onSelectedItemChanged?.call(index);
253 254
  }

255 256 257
  /// Draws the selectionOverlay.
  Widget _buildSelectionOverlay(Widget selectionOverlay) {
    final double height = widget.itemExtent * widget.magnification;
258 259

    return IgnorePointer(
260
      child: Center(
261
        child: ConstrainedBox(
262
          constraints: BoxConstraints.expand(
263
            height: height,
264
          ),
265
          child: selectionOverlay,
266 267 268 269 270
        ),
      ),
    );
  }

271 272
  @override
  Widget build(BuildContext context) {
273
    final TextStyle textStyle = CupertinoTheme.of(context).textTheme.pickerTextStyle;
274
    final Color? resolvedBackgroundColor = CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context);
275

276
    assert(RenderListWheelViewport.defaultPerspective == _kDefaultPerspective);
277
    final Widget result = DefaultTextStyle(
278
      style: textStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(textStyle.color, context)),
279 280 281 282
      child: Stack(
        children: <Widget>[
          Positioned.fill(
            child: _CupertinoPickerSemantics(
283
              scrollController: widget.scrollController ?? _controller!,
284 285 286 287 288 289 290
              child: ListWheelScrollView.useDelegate(
                controller: widget.scrollController ?? _controller,
                physics: const FixedExtentScrollPhysics(),
                diameterRatio: widget.diameterRatio,
                offAxisFraction: widget.offAxisFraction,
                useMagnifier: widget.useMagnifier,
                magnification: widget.magnification,
291
                overAndUnderCenterOpacity: _kOverAndUnderCenterOpacity,
292 293 294 295 296
                itemExtent: widget.itemExtent,
                squeeze: widget.squeeze,
                onSelectedItemChanged: _handleSelectedItemChanged,
                childDelegate: widget.childDelegate,
              ),
297
            ),
298
          ),
299 300
          if (widget.selectionOverlay != null)
            _buildSelectionOverlay(widget.selectionOverlay!),
301 302
        ],
      ),
303
    );
304 305 306 307 308

    return DecoratedBox(
      decoration: BoxDecoration(color: resolvedBackgroundColor),
      child: result,
    );
309 310
  }
}
311

312 313 314 315 316 317 318 319 320 321
/// A default selection overlay for [CupertinoPicker]s.
///
/// It draws a gray rounded rectangle to match the picker visuals introduced in
/// iOS 14.
///
/// This widget is typically only used in [CupertinoPicker.selectionOverlay].
/// In an iOS 14 multi-column picker, the selection overlay is a single rounded
/// rectangle that spans the entire multi-column picker.
/// To achieve the same effect using [CupertinoPickerDefaultSelectionOverlay],
/// the additional margin and corner radii on the left or the right side can be
322
/// disabled by turning off [capStartEdge] and [capEndEdge], so this selection
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/// overlay visually connects with selection overlays of adjoining
/// [CupertinoPicker]s (i.e., other "column"s).
///
/// See also:
///
///  * [CupertinoPicker], which uses this widget as its default [CupertinoPicker.selectionOverlay].
class CupertinoPickerDefaultSelectionOverlay extends StatelessWidget {

  /// Creates an iOS 14 style selection overlay that highlights the magnified
  /// area (or the currently selected item, depending on how you described it
  /// elsewhere) of a [CupertinoPicker].
  ///
  /// The [background] argument default value is [CupertinoColors.tertiarySystemFill].
  /// It must be non-null.
  ///
338
  /// The [capStartEdge] and [capEndEdge] arguments decide whether to add a
339 340 341 342
  /// default margin and use rounded corners on the left and right side of the
  /// rectangular overlay.
  /// Default to true and must not be null.
  const CupertinoPickerDefaultSelectionOverlay({
343
    super.key,
344
    this.background = CupertinoColors.tertiarySystemFill,
345 346
    this.capStartEdge = true,
    this.capEndEdge = true,
347
  });
348

349 350
  /// Whether to use the default use rounded corners and margin on the start side.
  final bool capStartEdge;
351

352 353
  /// Whether to use the default use rounded corners and margin on the end side.
  final bool capEndEdge;
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

  /// The color to fill in the background of the [CupertinoPickerDefaultSelectionOverlay].
  /// It Support for use [CupertinoDynamicColor].
  ///
  /// Typically this should not be set to a fully opaque color, as the currently
  /// selected item of the underlying [CupertinoPicker] should remain visible.
  /// Defaults to [CupertinoColors.tertiarySystemFill].
  final Color background;

  /// Default margin of the 'SelectionOverlay'.
  static const double _defaultSelectionOverlayHorizontalMargin = 9;

  /// Default radius of the 'SelectionOverlay'.
  static const double _defaultSelectionOverlayRadius = 8;

  @override
  Widget build(BuildContext context) {
    const Radius radius = Radius.circular(_defaultSelectionOverlayRadius);

    return Container(
374 375 376
      margin: EdgeInsetsDirectional.only(
        start: capStartEdge ? _defaultSelectionOverlayHorizontalMargin : 0,
        end: capEndEdge ? _defaultSelectionOverlayHorizontalMargin : 0,
377 378
      ),
      decoration: BoxDecoration(
379 380 381
        borderRadius: BorderRadiusDirectional.horizontal(
          start: capStartEdge ? radius : Radius.zero,
          end: capEndEdge ? radius : Radius.zero,
382 383 384 385 386 387 388
        ),
        color: CupertinoDynamicColor.resolve(background, context),
      ),
    );
  }
}

389 390 391 392 393 394 395 396
// Turns the scroll semantics of the ListView into a single adjustable semantics
// node. This is done by removing all of the child semantics of the scroll
// wheel and using the scroll indexes to look up the current, previous, and
// next semantic label. This label is then turned into the value of a new
// adjustable semantic node, with adjustment callbacks wired to move the
// scroll controller.
class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget {
  const _CupertinoPickerSemantics({
397
    super.child,
398
    required this.scrollController,
399
  });
400 401 402 403

  final FixedExtentScrollController scrollController;

  @override
404 405
  RenderObject createRenderObject(BuildContext context) {
    assert(debugCheckHasDirectionality(context));
406
    return _RenderCupertinoPickerSemantics(scrollController, Directionality.of(context));
407
  }
408 409 410

  @override
  void updateRenderObject(BuildContext context, covariant _RenderCupertinoPickerSemantics renderObject) {
411
    assert(debugCheckHasDirectionality(context));
412
    renderObject
413
      ..textDirection = Directionality.of(context)
414 415 416 417 418 419
      ..controller = scrollController;
  }
}

class _RenderCupertinoPickerSemantics extends RenderProxyBox {
  _RenderCupertinoPickerSemantics(FixedExtentScrollController controller, this._textDirection) {
420
    _updateController(null, controller);
421 422 423
  }

  FixedExtentScrollController get controller => _controller;
424 425 426
  late FixedExtentScrollController _controller;
  set controller(FixedExtentScrollController value) => _updateController(_controller, value);

427
  // This method exists to allow controller to be non-null. It is only called with a null oldValue from constructor.
428
  void _updateController(FixedExtentScrollController? oldValue, FixedExtentScrollController value) {
429
    if (value == oldValue) {
430
      return;
431 432
    }
    if (oldValue != null) {
433
      oldValue.removeListener(_handleScrollUpdate);
434
    } else {
435
      _currentIndex = value.initialItem;
436
    }
437 438 439 440 441 442 443
    value.addListener(_handleScrollUpdate);
    _controller = value;
  }

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
444
    if (textDirection == value) {
445
      return;
446
    }
447 448 449 450 451 452 453 454 455 456 457 458
    _textDirection = value;
    markNeedsSemanticsUpdate();
  }

  int _currentIndex = 0;

  void _handleIncrease() {
    controller.jumpToItem(_currentIndex + 1);
  }

  void _handleDecrease() {
    controller.jumpToItem(_currentIndex - 1);
459
  }
460 461

  void _handleScrollUpdate() {
462
    if (controller.selectedItem == _currentIndex) {
463
      return;
464
    }
465 466 467
    _currentIndex = controller.selectedItem;
    markNeedsSemanticsUpdate();
  }
468
  @override
469 470 471 472 473 474 475 476
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
    config.textDirection = textDirection;
  }

  @override
  void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {
477
    if (children.isEmpty) {
478
      return super.assembleSemanticsNode(node, config, children);
479
    }
480 481 482 483
    final SemanticsNode scrollable = children.first;
    final Map<int, SemanticsNode> indexedChildren = <int, SemanticsNode>{};
    scrollable.visitChildren((SemanticsNode child) {
      assert(child.indexInParent != null);
484
      indexedChildren[child.indexInParent!] = child;
485 486 487 488 489
      return true;
    });
    if (indexedChildren[_currentIndex] == null) {
      return node.updateWith(config: config);
    }
490 491 492
    config.value = indexedChildren[_currentIndex]!.label;
    final SemanticsNode? previousChild = indexedChildren[_currentIndex - 1];
    final SemanticsNode? nextChild = indexedChildren[_currentIndex + 1];
493 494 495 496 497 498 499 500 501 502
    if (nextChild != null) {
      config.increasedValue = nextChild.label;
      config.onIncrease = _handleIncrease;
    }
    if (previousChild != null) {
      config.decreasedValue = previousChild.label;
      config.onDecrease = _handleDecrease;
    }
    node.updateWith(config: config);
  }
503 504 505 506 507 508

  @override
  void dispose() {
    super.dispose();
    controller.removeListener(_handleScrollUpdate);
  }
509
}