Flutter: keeping scrollOffset when adding new elements to list

Viewed 187

I have CustomScrollView and in it Two SliverList, it's because when I scroll to the top and I download new elements to list, these new elements are added to top list and its mainting scroll on bottom list (maintating on top of bottom list) cause CustomScrollView have center on bottom list.

I'm usin bloc around the custom scroll view for elements that im rendering. Problem is that when I download new elements on background and person is scrolled in second list it immedietly gets scrolled to top of that second list. I dont want that, I want to keep him on his scrolled position and just inform him "Hey there are new information on top".

CustomScrollView(
        center: _mainListKey,
        controller: widget.scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        slivers: [
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) =>
                  NewElement(),
              childCount: newElements?.length ?? 0,
            ),
          ),
          SliverList(
            key: _mainListKey,
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) => OldElement(),
              childCount: oldElements.length,
            ),
          ),
        ],
      ),
1 Answers

I would recommend having a list of items defined above the build such like

final itemsToDisplay = <Type>[];
@override
Widget build(BuildContext context) { ...

then you can use either BlocBuilder or context.read in order to listen for the update and if the state is the one that you are interested in you would just append to the list. Flutter should figure out which items has been updated and keep the list at the same position.

class ListWithBloc extends StatelessWidget {
  ListWithBloc({Key? key}) : super(key: key);

  final itemsToDisplay = <dynamic>[];

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ListBloc, ListState>(
      builder: (context, state) {
        if (state is ListUpdated) {
          itemsToDisplay.add(state.newItems).toSet().toList();
        }
      },
      child: ListView(
        children: Widget(),
      ),
    );
  }
}

Let me know if this was helpful! I hope it works for you.

Related