I have an image which has large width which has horizontal scroll. There is a list below that. The image is fixed. I want to scroll the image horizontally when scrolling the list vertically. How to connect these two widgets in flutter? Is it possible to do this in flutter?
The use case is list has many items. When we scroll to a particular item we need to scroll the image to a particular point. Thanks.
2
Answers
Wrapping your-
ListView.builder
withExpanded
Widget & settingmainAxisSize: MainAxisSize.min,
ofColumn
Widget.E.x Code .
You could wrap the image that you want to scroll horizontally in a
SingleChildScrollView
, and will most likely use aListView
for your vertically scrolling list. Both of these widgets have acontroller
property, that’s where you can connect the scroll position of the two.If you want to control the scrolling position of your image based on the scrolling position of your list, you need to read the
offset
of the controller of your list every time it changes (when the user scrolls the list). Then you need to correct this value with the ratio of the physical length of the two scrolling widgets. You can get this value by callingcontroller.position.maxScrollExtent
. This step is needed because theoffset
of the scroll controllers is an absolute value. Then call thejumpTo()
method of the controller of the horizontally scrolling image with the value you calculated in the previous step.Below is an example where the position of the horizontally scrolling bar is kept in sync with the scroll position of the
ListView
. I used aContainer
instead of a wide image, but the idea is the same. The bar will stay in sync with the list regardless of their relative size. You can test it by changing the number of the list tiles or the width of theContainer
.