Scroll in ListView Flutter
Flutter Scroll Down to Bottom or Top of List in ListViewIn this tutorial, we will learn how to scroll down to the bottom of a ListView in Flutter. Scrolling down to the bottom of the list is very boring and so here is a way to scroll directly to the bottom or top of the list. Show Project Setup:Below is a starter code so that you can follow along with this tutorial. This code generates an app with a list of 100 items. Dart
Run the code and the result will be as follows. Starter code Implementation:As you can see our FloatingActionButton is not working as no function is assigned to it in the onPressed field. First of all, we will need a ScrollController to control our ListView. So create a ScrollController. Dart
Now assign this ScrollController to the controller field of ListView. Dart
Now come to the onPressed() field of FloatingActionButton. Here we will use the following code: Dart
We have first checked whether we can communicate with the members of ScrollController using Dart
If not checked, we will get a runtime error. The above code returns a boolean value. Now moving to the next part, we asked for the maximum scrolling extent of the ScrollController. Dart
This simply means we are asking for the last position in the ListView via ScrollController. And then, we asked the ScrollController to move the position we got above using the jumpTo function. Dart
Now run the code and you will see the following result. Scroll down list So we have successfully reached the bottom of our list. Now you may think that it would be nice if not moving abruptly to the bottom of the list, we will go easily. So the same can be achieved using the animateTo function. Replace the jumpTo code with the code below: Dart
Now run the app again. You will see the following result. Animated Scrolling We have learned how to scroll down the list, now we will learn how to scroll to the top of the ListView. Instead of getting the maxScrollExtent, we will now use the minScrollExtent from ScrollController and that simply means the top position of ListView. Here is the code and dont forget to change the Icon: Dart
Now run the app again. Scrolling top of ListView Complete Source Code:Dart
Output: Scroll to the bottom of the list Scroll to the top of the list Conclusion:In this tutorial, we have learned a very interesting feature of ListView that you may have come across on many websites and blogs. So now you can also implement the same feature in your app.
Article Tags :
Dart Flutter
Flutter Flutter-widgets
Read Full Article
|