hewa jalal
hewa jalal

Reputation: 963

Flutter how to Programmatically scroll to the next item in the list?

i want to have my list be controlled by arrow buttons, one that moves it forward one item and one that moves it backward one item something like this

enter image description here

i tried many packages and solutions but most of them goes to the end of the list or a fixed index number what i want is for the list to move to the next item in the list

Upvotes: 0

Views: 4764

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You can use scroll_to_index package providing AutoScrollTag.

class ST extends StatefulWidget {
  const ST({Key? key}) : super(key: key);

  @override
  _STState createState() => _STState();
}

class _STState extends State<ST> {
  final AutoScrollController controller = AutoScrollController();

  late List<Widget> items;

  int _currentFocusedIndex = 0;

  @override
  void initState() {
    items = List.generate(
      33,
      (index) => AutoScrollTag(
        key: ValueKey(index),
        controller: controller,
        index: index,
        child: Container(
          height: 100,
          width: 100,
          alignment: Alignment.center,
          color: index.isEven ? Colors.deepOrange : Colors.deepPurple,
          child: Text(index.toString()),
        ),
      ),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: [
          IconButton(
            onPressed: () {
              _currentFocusedIndex--;
              if (_currentFocusedIndex < 0) {
                _currentFocusedIndex = items.length - 1;
              }

              controller.scrollToIndex(_currentFocusedIndex,
                  preferPosition: AutoScrollPosition.begin);

              setState(() {});
            },
            icon: const Icon(Icons.arrow_back_ios_new_sharp),
          ),
          Expanded(
            child: ListView(
              scrollDirection: Axis.horizontal,
              controller: controller,
              children: items,
            ),
          ),
          IconButton(
            onPressed: () {
              _currentFocusedIndex++;
              if (_currentFocusedIndex > items.length) {
                _currentFocusedIndex = 0;
              }
              controller.scrollToIndex(_currentFocusedIndex,
                  preferPosition: AutoScrollPosition.begin);
              setState(() {});
            },
            icon: const Icon(Icons.arrow_forward_ios_sharp),
          ),
        ],
      ),
    );
  }
}

Upvotes: 3

Ujjwal Raijada
Ujjwal Raijada

Reputation: 975

It can be done only if you know the exact width to be scrolled. Use scrollController

ScrollController scrollController = ScrollController(
  initialScrollOffset: 100, // or whatever offset you wish
  keepScrollOffset: true,
);

Upvotes: 0

Related Questions