Reputation: 587
If I add items dynamically to a listView with a listView.builder, how do I keep the bottom of the list focus ? Like if the list is full, and I add an Item, how do I do to make the other go up and focus the last item without deleting anything ?
Upvotes: 2
Views: 9198
Reputation: 327
This solution keeps the ListView
focused at the bottom by default, and does not require any scroll controller. So you don't have to worry about where to initialze your scroll controller 😉.
int list_length; // length of your very long list
List long_list; // your long list of items
ListView.builder(
reverse: true,
shrinkWrap: true,
itemCount: item_length,
itemBuilder: (context, index)=>Text(
'${long_list[list_length-index-1]}'
))
)
Happy Coding !!
Upvotes: 0
Reputation: 1426
These answers don't make your list Focused at the bottom by default, I used this trick hope it helps :
first reverse the list you gave to the ListView.builder
an then add this property to your ListView : reverse: true
Upvotes: 1
Reputation: 2426
The Accepted answer is correct but also this answer will be useful,
//Controller
ScrollController _scrollController = new ScrollController();
//Add this controller to list
ListView.builder(
controller: _scrollController, //The Controller
shrinkWrap: true,
reverse: false,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
//Your Widgets
})
// Add this to everytime you want to scroll to the bottm of list
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
Upvotes: 3
Reputation: 4705
Hi you can take help of ScrollController
using method jumpTo()
or animateTo()
like bellow,
First create instance of
ScrollController controller = new ScrollController();
Then after registering it with your listview like bellow example
ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text("Item List"),
),
controller: controller,
itemCount: 50,
),
And finally call jumTo() or animateTo()
method when new item added or whenever you want to go at bottom like bellow
controller.jumpTo(controller.position.maxScrollExtent);
Upvotes: 4