How can I add an element to the end of a Listview.builder
which allows the user to click it and make him go back to the top of the list?
Pass a scroll controller to ListView.builder
and add one to item count which is used to add "back to top" button as the last item. Then you can use listView controller to scroll the list to top when user tap on the last item of the list.
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: _controller,
itemCount: items.length + 1,
itemBuilder: (context, index) => (index != items.length)
? ListTile(title: Text(items[index]))
: ListTile(
leading: IconButton(
icon: Icon(Icons.keyboard_arrow_up),
onPressed: _navigateToTop),
),
),
);
}
void _navigateToTop() {
final Duration duration = Duration(milliseconds: 400);
final Curve curve = Curves.ease;
if (_controller.hasClients) {
var scrollPosition = this._controller.position;
scrollPosition.animateTo(
0,
duration: duration,
curve: curve,
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With