flutterlistviewscrolljump-list

Flutter: Jump to specific item by item data in ListView.builder


It's possible to jump to specific item by item data in ListView?

class Test extends StatelessWidget {
  Test({Key? key}) : super(key: key);

  final _list = <String>[
    "INFWARS_CH01_EP01",
    "INFWARS_CH01_EP02",
    "INFWARS_CH01_EP03",
    "INFWARS_CH01_EP04",
    "INFWARS_CH01_EP05",
  ];

  void _scrollToItem() {
    final specificItem = "INFWARS_CH01_EP04";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: _list.length,
        itemBuilder: (context, index) {
          final data = _list[index];
          return Text(data);
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _scrollToItem(),
      ),
    );
  }
}

as you can see, I want to jump to specific item in ListView by specific data "INFWARS_CH01_EP04" using _scrollToItem function, not by index or by position.

So the item ListView for INFWARS_CH01_EP04 will be in the top (scrolled). For now in the top is INFWARS_CH01_EP01.

It's possible to do it?


Solution

  • I fix it using this package: https://pub.dev/packages/scroll_to_index

    So you can scroll / jump to specific item by index / by item data in ListView.

    class Test extends StatelessWidget {
      Test({Key? key}) : super(key: key);
      AutoScrollController _scrollController = AutoScrollController();
    
      final _list = <String>[
        "INFWARS_CH01_EP01",
        "INFWARS_CH01_EP02",
        "INFWARS_CH01_EP03",
        "INFWARS_CH01_EP04",
      ];
    
      void _scrollToItem() async {
        final specificItem = "INFWARS_CH01_EP04";
        final index = _list.indexOf(specificItem);
        await _scrollController.scrollToIndex(
          index,
          preferPosition: AutoScrollPosition.begin,
        );
        await _scrollController.highlight(index);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView.builder(
            controller: _scrollController,
            itemCount: _list.length,
            itemBuilder: (context, index) {
              final data = _list[index];
              return AutoScrollTag(
                  key: ValueKey(index),
                  controller: _scrollController,
                  index: index,
                  child: Text(data),
              );
            },
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () => _scrollToItem(),
          ),
        );
      }
    }