Scroll to top ListView flutter
Flutter ListViewis very easy to use, and very versatile. As an Android developer used to creating Adaptersfor my RecyclerViews, I appreciate the simplicity of Flutter. However, one often used functionality is lacking, and it is smoothScrollToPosition(int position). Show There is currently an open github issue requesting this very feature. In the meanwhile, for lists where all items have the same height, there is a trick you can use. Scroll to position for Flutter lists where all items have the same heightTo follow the code tutorial, create a new app as follows. create new app
If youre unsure how to set up a Flutter app, check outGetting started with Flutterofficial tutorial. In main.dart, we launch the app as below. main.dart
This wont build until we create ListPage. So lets create a new folder list in lib folder, and add the file list_view.dartto it. Looking for a Flutter job?Check out my job board dedicated to Flutter at flutterjobs.infoListPage widgetFirstly, we set up the ListPage widget, which consists of 2 buttons at the top, and a list of items below. list/list_view.dart
Now, you can run the app to view the list and the 2 buttons above it. Scroll ControllerSecondly, we create a ScrollController initState()
and add it to the itemsWidget. build(BuildContext context)/itemsWidget
Selected ItemThirdly, to implement the scrolling functionality, we are going to add a selected property to Item Item
and update the items in initState() initState()
Scroll to selected itemFourthly, when building the Widget, it will scroll to the first found selected item. Add this tobuild(BuildContext context). build(BuildContext context)
ButtonsFinally, lets wire our 2 buttons. _scrollToOranges()
_scrollToTomatoes
Voila!We can now scroll to a specific item when a Flutter ListView has a fixed height. What next?Subscribe to the open github issue requesting a method to programmatically scroll a Flutter ListView to a given position. Check out Being a software developer in 2020!Natalie Masse Hooper RelatedAuthor: Natalie Masse HooperMobile app developer. 11 years experience with the Android SDK, 4 years with Flutter. Past apps range from start ups to large tech (Google) and non tech (British Airways) companies.LinkedInnatalie ( at ) cogitas (dot) net View all posts by Natalie Masse Hooper |