I need to display a very large collection of elements (images from files) in a ListView
, using the usual ListView.builder
constructor. I statically know the size of each element so, technically, I know also the total height of the list view.
The problem is that I need to programmatically scroll up or down in a position of the list, using a ScrollController
associated to the list.
In iOS, the same scenario can be resolved using a TableView
, and it is possible to instruct the underlining framework about the correct size of each element, without the necessity to pre-build each element to know the correct size (that is what Flutter should perform in order to scroll up or down the list).
For my knowledge, it is not possible to instruct Flutter about the size of each list element, but I think that this information could be extremely useful to create a more optimized list view, at least in this particular case.
Do you know about any library or other possibility to improve this logic?
2
Answers
Create a ScrollController object:
Associate the ScrollController with your ListView:
Determine the position you want to scroll to. Let’s say you have the index of the element you want to scroll to as targetIndex.
Calculate the scroll offset based on the size of your elements and the target index. Assuming each element has a fixed height of itemHeight:
Scroll to the calculated offset using the ScrollController’s animateTo method:
This will smoothly scroll to the desired position within the list.
replace ListView.builder with your actual implementation, and adjust the variables and values according to your specific use case.
I think the best solution is a package named
scrollable_positioned_list
: A flutter list that allows scrolling to a specific item in the list and it’s a google package.Link to the package on pub dev
A ScrollablePositionedList works much like the builder version of ListView except that the list can be scrolled or jumped to a specific item.
A ScrollablePositionedList can be created with:
One then can scroll to a particular item with: