2

Problems: For example, there is a list of 100 messages. The current viewport of CustomCrollView is showing message 50 -> 60. When adding a new item to the start of the list, the viewport jumps to message 49 (old) -> 59 (old) (because the scroll offset is not changed so it shifts the content down).

Expected: After adding item, the viewport should keep showing message 50 (old) -> 60 (old).

How can I implement that?

dante
  • 984
  • 3
  • 10
  • 24
  • is using scrollcontroller to cache the offset before add new item and then use jumpto(...) possible to solve your case? – CbL May 14 '22 at 04:41
  • Maybe, but I don't know how to add a listener when the maxScrollExtent is changed. I think I can compare the maxScrollExtent to increase the offset. – dante May 14 '22 at 04:47
  • i see. or is it ok to listen the list of msg is expanding instead of listening to the maxScrollExtent? just temp alternative. if anyone knows the way to listen to change of maxScrollExtent, i am also very interested. – CbL May 14 '22 at 05:02
  • But I don't know how big is the new message. And I just tried to set the new offset using WidgetsBinding.addPostFrameCallback, but it blink for one frame. – dante May 14 '22 at 05:07
  • any solutions yet?? I have the same problem – Alex Amatobi Jul 07 '23 at 12:14

1 Answers1

1

If you don't mind using two list. Try it using centerKey with CustomScrollView. The first list for new item and the second list for you initial item. When you adding new item to the start, just add item to the first list and the viewport will not jump.

 @override
  Widget build(BuildContext context) {
    const Key centerKey = ValueKey('second-sliver-list');
    return Scaffold(
      body: CustomScrollView(
        center: centerKey,
        slivers: [
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final item = newList[index];
                return ListTile(
                  title: Text('${item.id} ${item.name}'),
                );
              },
              childCount: newList.length,
            ),
          ),
          SliverList(
            key: centerKey,
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final item = myList[index];
                return ListTile(
                  title: Text('${item.id} ${item.name}'),
                );
              },
              childCount: myList.length,
            ),
          ),
        ],
      ),
    );
  }
Fajrul
  • 19
  • 5