Gustavo Barrios
Gustavo Barrios

Reputation: 73

How can I focus the last item of a listView in flutter

I'm trying to make my listview always focus on the last element in a chat, but I don't know how to do it, I appreciate if someone can help me

Widget ChatMessageList(){
    return StreamBuilder(
      stream: chatMessageStream,
      builder: (context, snapshot){
        return snapshot.hasData ? ListView.builder(
          controller: _scrollController,
          itemCount: snapshot.data.documents.length,
          itemBuilder: (context, index){
            return MessageTile(snapshot.data.documents[index].data()['message'],
                snapshot.data.documents[index].data()['sendBy'] == userSnapshop.uid);
          }
        ) : Container();
      },
    );
  }

Upvotes: 4

Views: 8205

Answers (2)

ajay
ajay

Reputation: 1000

List view can be reverse by wrapping another scrollable widget.

so you just need to wrap your ListView by SingleChildScrollView and change the reading direction by revers property.

SingleChildScrollView(
        reverse: true,
        child: ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: 100,
          itemBuilder: (context, index) => Text(
            index.toString(),
          ),
        ),
      )

Upvotes: 14

rstrelba
rstrelba

Reputation: 1954

  _animateToLast() {
    debugPrint('scroll down');
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      curve: Curves.easeOut,
      duration: const Duration(milliseconds: 500),
    );
  }

Upvotes: 0

Related Questions