Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an element at the end of ListView.builder to move back to the top?

Tags:

flutter

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?

like image 961
Tizi Dev Avatar asked Oct 17 '25 02:10

Tizi Dev


1 Answers

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,
      );
    }
  }
like image 84
RaSha Avatar answered Oct 18 '25 20:10

RaSha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!