Select ListView 的中心项 Flutter

Select center item of ListView Flutter

我需要实现一个可滚动的列表,以便自动突出显示中心的元素。如何跟踪中心元素并不断突出它?

您需要 ScrollController 来设置列表的初始位置(偏移量)。这是我将 initialScrollOffset 定义为 itemHeight 乘以您希望可见的项目的 index 的示例(在我的例子中,它是您要求的中间项目):

@override
  Widget build(BuildContext context) {
    List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // 5 is in the middle
    double itemHeight = 30;
    // or you can pass index of the item you want to be visible
    var selectedItem = list[(list.length / 2).toInt()];
    var scrollController = ScrollController(
        initialScrollOffset: selectedItem * itemHeight); // 5 should be visible
    return Scaffold(
      body: SizedBox(
        height: 100,
        child: ListView(
          controller: scrollController,
          children: list
              .map(
                (element) => Container(
                  height: itemHeight,
                  padding: const EdgeInsets.all(5),
                  margin: const EdgeInsets.symmetric(vertical: 5),
                  child: Text(
                    element.toString(),
                  ),
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                        side: BorderSide(
                          color: selectedItem == element
                              ? Colors.purple
                              : Colors.transparent,
                          width: 2,
                        )),
                  ),
                ),
              )
              .toList(),
        ),
      ),
    );
  }

您可以使用 CupertinoPicker 小部件

int _selectedValue = 0;

CupertinoPicker(
        backgroundColor: Colors.white,
        itemExtent: 30,
        scrollController: FixedExtentScrollController(initialItem: 1),
        children: [
        Text('10:00'),
        Text('7KW'),
        Text('11:00'),
        ],
        onSelectedItemChanged: (value) {
           setState(() {
                    _selectedValue = value;
           });
   },