Search code examples
flutterdartscrollscrollviewglobal-key

Scrollable.ensureVisible(); not working if the widget is out of view?


I use Scrollable.ensureVisible(GlobalObjectKey(category?.id).currentContext); this code to scroll particular widget.

This is not working if the target widget is out of view.

For example I have a list 1 to 10. If I scroll 1 to 2 and 2 to 3 or 3 to 4 it's working smoothly. But if I go to 1 to 5 or 5 to 1 it's not working

And the code is,

return Container(
    key: GlobalObjectKey(category[index].id),

I use the below code to move to particular widget

InkWell(
  onTap: () {
Scrollable.ensureVisible(GlobalObjectKey(category?.id).currentContext);

Any help will be highly appriciated. Thanks in advance


Solution

  • If you use a ListView in flutter the index is only available for the visible widgets. A common solution would be to exchange ListView with

    SingleChildScrollView(
      child: Column(
        children: [
          Container(key: myKey, child: ...),
          ..all your widgets of your previous ListView
        ]
    
    void scrollTo(GlobalKey itemKey) async {
      final context = itemKey.currentContext!;
      await Scrollable.ensureVisible(context);
    }
    

    now you can call scrollTo with your itemKey and the list will scroll to the respective item.