Max
Max

Reputation: 1301

Select center item of ListView Flutter

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

Upvotes: 0

Views: 1956

Answers (2)

Ante Bule
Ante Bule

Reputation: 2136

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

Upvotes: 3

Jaydeep chatrola
Jaydeep chatrola

Reputation: 2701

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

Upvotes: 1

Related Questions