Home > other >  Select center item of ListView Flutter
Select center item of ListView Flutter

Time:04-29

Tell me, you need to implement such a scrollable list, and so that the element in the center is automatically highlighted. How to keep track of the central element and constantly highlight it?

enter image description here

CodePudding user response:

You need to have ScrollController to set initial position (offset) of your list. Here is the example where I defined initialScrollOffset as a result of itemHeight multiplied by index of the item that you want to be visible (in my case it's the middle item as you've requested):

@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(),
        ),
      ),
    );
  }

CodePudding user response:

you can use CupertinoPicker widget

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;
           });
   },
  • Related