如何在 Flutter 中显示列表的中间元素?

How to display the middle element of a list in Flutter?

我有一个类似 CupertinoPicker 的小部件,但它是手工制作的。我需要默认选择列表的中间元素,而不是现在的初始元素。我尝试了不同的选择,但还没有做到。请告诉我如何实现这个,我将不胜感激?

小部件

class WheelSpeedPicker extends StatefulWidget {
  final Function(dynamic) onValueChanged;
  final int? startPosition;
  final double itemSize;
  final double? listHeight;
  final int currentPosition;
  final double? listWidth;
  final FixedExtentScrollController? controller;

  const WheelSpeedPicker({
    Key? key,
    required this.onValueChanged,
    required this.currentPosition,
    required this.itemSize,
    this.startPosition,
    this.listHeight,
    this.controller,
    this.listWidth,
  }) : super(key: key);

  @override
  _WheelTimePickerState createState() {
    return _WheelTimePickerState();
  }
}

class _WheelTimePickerState extends State<WheelSpeedPicker> {
  FixedExtentScrollController? fixedExtentScrollController;
  int? currentPosition;

  @override
  void initState() {
    super.initState();
    currentPosition = widget.currentPosition;
    fixedExtentScrollController = widget.controller ??
        FixedExtentScrollController(initialItem: currentPosition ?? 0);
  }

  void _listener(int position) {
    setState(() {
      currentPosition = position;
    });
    widget.onValueChanged(currentPosition);
  }

 

  @override
  void initState() {
    super.initState();
    // swap this
    // currentPosition = widget.currentPosition;
    // with this
    currentPosition = (time.length / 2).floor();
    fixedExtentScrollController = widget.controller ??
        FixedExtentScrollController(initialItem: currentPosition ?? 0);
  }

除此之外,我认为如果您将项目列表添加到小部件参数,您的小部件会更有用:


class WheelSpeedPicker extends StatefulWidget {
  final Function(dynamic) onValueChanged;
  final List<String> items;
  final int? startPosition;
  final double itemSize;
  final double? listHeight;
  final int currentPosition;
  final double? listWidth;
  final FixedExtentScrollController? controller;

  const WheelSpeedPicker({
    Key? key,
    required this.items,
    required this.onValueChanged,
    required this.currentPosition,
    required this.itemSize,
    this.startPosition,
    this.listHeight,
    this.controller,
    this.listWidth,
  }) : super(key: key);

然后你会有一组更连贯的参数,因为你已经在界面中有一个 startPosition。

@override
  void initState() {
    super.initState();
    currentPosition = widget.startPosition;
    fixedExtentScrollController = widget.controller ??
        FixedExtentScrollController(initialItem: startPosition ?? 0);
  }