Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically scroll to an element in ListView.builder?

Tags:

flutter

dart

My goal is to scroll to the correct person when I tap the marker in GoogleMaps. Each marker has already saved a reference to the respective index in the list, but i don't know how I can make the list scroll by itself. Thanks for any help :)

Screenshot of map & horizontal list

like image 808
jannik Avatar asked Jan 16 '20 23:01

jannik


People also ask

What is widget we use in the Talk to scroll to specific position in list?

A scroll controller creates a [ScrollPosition] to manage the state-specific to an individual [Scrollable] widget. To use a custom [ScrollPosition], subclass [ScrollController] and override [createScrollPosition]. A [ScrollController] is a [Listenable].

Is ListView builder scrollable?

ListView is the most commonly used scrolling widget. It displays its children one after another in the scroll direction. In the cross axis, the children are required to fill the ListView.

How do you scroll to a widget in flutter?

All you have to do is set Global Keys for your widgets and call Scrollable. ensureVisible on the key of your widget you want to scroll to. For this to work your ListView should be a finite List of objects. If you are using ListView.


1 Answers

You can assign a GlobalKey to the item you want to scroll to and make use of ScrollPosition.ensureVisible.

GlobalKey

You need the global key in order to access the RenderObject of your widget.
You will need to either store this global key as a variable in your StatefulWidget (preferrably).

ScrollController

You will also need to store a scroll controller in order to scroll to the position of your list view.


Here is how you would do it in the State of your widget:

final itemKey = GlobalKey();
final scrollController = ScrollController();

@override
void dispose() {
  scrollController.dispose();
  super.dispose();
}

@override
Widget build(BuildContext context) {
  // Return your widget tree in here.
  // I am only showing the ListView section.
  ...
  ListView(
    ...,
    controller: scrollController,
    // You can also use a builder list view or w/e else.
    // You only need to supply the GlobalKey to exactly one item.
    children: <Widget>[
       SomeWidget(
         key: itemKey,
         ...,
       ),
    ],
  )
  ...
}

Now, you will be able to scroll to your selected item:

scrollController.position.ensureVisible(
  itemKey.currentContext.findRenderObject()!,
  alignment: 0.5, // How far into view the item should be scrolled (between 0 and 1).
  duration: const Duration(seconds: 1),
);
like image 100
creativecreatorormaybenot Avatar answered Oct 31 '22 01:10

creativecreatorormaybenot