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 :)
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].
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.
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.
You can assign a GlobalKey
to the item you want to scroll to and make use of ScrollPosition.ensureVisible
.
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),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With