0

I have a comments and replies system. Replies against comments I want to make nested listview scroll all the way to bottom when a reply is added, right now, it takes me to the bottom of second last reply, but not to the last reply I added What I want

What I have, it scrolls to second last reply, not to last reply

void main() => runApp(MaterialApp(
      home: CommentScreen(),
    ));

class Comment {
  int id;
  String text;
  List<String> replies;

  Comment(this.id,this.text, {this.replies = const []});
}

class CommentScreen extends StatefulWidget {
  @override
  _CommentScreenState createState() => _CommentScreenState();
}
class _CommentScreenState extends State<CommentScreen> {
  List<Comment> comments = [
    Comment(1,"First comment", replies: ["Reply 1", "Reply 2"]),
    Comment(2,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(3,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(4,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(5,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(6,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(7,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(8,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(9,"Second comment",replies: ["Reply 1", "Reply 2"]),
    Comment(10,"Second comment", replies: ["Reply 1", "Reply 2"]),
  ];

  ScrollController _scrollController = ScrollController();

  void addReply(int commentIndex, String reply,int id) {
    setState(() {
      comments[commentIndex].replies.add(reply);
    });
    Scrollable.ensureVisible(GlobalObjectKey(id).currentContext!,
      duration: Duration(milliseconds: 1), // duration for scrolling time
      alignment: 1,
      curve: Curves.easeInOutCubic,);
    // Scroll to the last reply
   /* _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Comments"),
      ),
      body: ListView.builder(

        itemCount: comments.length,
        physics: AlwaysScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          Comment comment = comments[index];
          return Column(
            children: [
              ListTile(
                title: Text(comment.text),
                trailing: ElevatedButton(
                  onPressed: () {
                  addReply(index, """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.""",comment.id);
                  },
                  child: Text("Reply"),
                ),
              ),
              // Display replies inside ListView
              ListView.builder(
                key: GlobalObjectKey(comment.id),
                shrinkWrap: true,
                physics: ClampingScrollPhysics(),
                itemCount: comment.replies.length,
                itemBuilder: (BuildContext context, int replyIndex) {
                  String reply = comment.replies[replyIndex];
                  return ListTile(
                    title: Text(reply),
                  );
                },
              ),
            ],
          );
        },
      ),
    );
  }
}
  • If you wanna split the scrolls of several lists, you should use NestedScrollView with SliverList not a listview. See the document of [NestedScrollView](https://api.flutter.dev/flutter/widgets/NestedScrollView-class.html) and [SliverList](https://api.flutter.dev/flutter/widgets/SliverList-class.html). – BG Park Jun 22 '23 at 10:18
  • I am using silver list with customscrollview, can you please suggest any example – Muhammad Ibrahim Jun 22 '23 at 10:46

1 Answers1

0
import 'package:flutter/material.dart';

class TestScrollView extends StatefulWidget {
  const TestScrollView({super.key});

  @override
  State<TestScrollView> createState() => _TestScrollViewState();
}

class _TestScrollViewState extends State<TestScrollView> {
  late final ScrollController scrollController;

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('TEST')),
      body: CustomScrollView(
        controller: scrollController,
        slivers: [
          SliverAppBar(
            // See the official document for understanding paramters.
            pinned: true,
            floating: false,
            collapsedHeight: 300.0, // Min height
            expandedHeight: 500.0, // Max height
            flexibleSpace: ListView.builder(
              itemBuilder: (context, index) => Text('Upper Item $index'),
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              childCount: 1000,
              (context, index) => Text('item $index'),
            ),
          ),
        ],
      ),
    );
  }
}

enter image description here

Here's an example. However, there are so many ways to use slivers. I think reading the official document is a best way to learn about slivers.

BG Park
  • 169
  • 7