【问题标题】:Flutter: keeping scrollOffset when adding new elements to listFlutter:将新元素添加到列表时保持滚动偏移
【发布时间】:2022-01-02 06:31:39
【问题描述】:

我有 CustomScrollView 并在其中有两个 SliverList,这是因为当我滚动到顶部并将新元素下载到列表时,这些新元素将添加到顶部列表中,并且在底部列表中保持滚动(保持在底部列表的顶部) 导致 CustomScrollView 在底部列表中居中。

我在我正在渲染的元素的自定义滚动视图周围使用 bloc。 问题是,当我在背景上下载新元素并且人在第二个列表中滚动时,它会立即滚动到第二个列表的顶部。我不想这样,我想让他保持滚动位置,然后告诉他“嘿,上面有新信息”。

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,
            ),
          ),
        ],
      ),

【问题讨论】:

    标签: flutter bloc


    【解决方案1】:

    我建议在构建上方定义一个项目列表,例如

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

    然后您可以使用 BlocBuilder 或 context.read 来监听更新,如果状态是您感兴趣的状态,您只需附加到列表中。 Flutter 应该找出哪些项目已经更新,并将列表保持在相同的位置。

    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(),
          ),
        );
      }
    }
    

    如果这有帮助,请告诉我!我希望它对你有用。

    【讨论】:

    • 感谢您的回答,不幸的是这不起作用。当我添加新元素并滚动时,它会自动滚动到顶部。顺便说一句,您想建议的可能不是 BlocBuilder 而是 BlocListener
    • 向将保留索引的图块添加键。
    • 另一件可能导致这种情况的事情是当您的模型没有扩展 Equatable 时。
    猜你喜欢
    • 2019-02-10
    • 2020-04-06
    • 2020-09-22
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多