返回

让 NestedScrollView 中的 Pinned 头部不再抖动,高能解决方法来啦!

Android

Flutter 扩展:巧妙解决 NestedScrollView 中 Pinned 头部导致的滚动抖动问题

NestedScrollView 组件通常用于在滚动视图中嵌套其他滚动视图,例如 ListView 或 GridView。Pinned Header 是一个特殊的 SliverPersistentHeader,它可以固定在滚动视图的顶部或底部。当滚动视图滚动时,Pinned Header 会保持固定不动。

但是,如果您在 NestedScrollView 中使用 Pinned Header,则可能会遇到滚动抖动的问题。这是因为,当 NestedScrollView 滚动时,它会不断更新 SliverPersistentHeader 的位置。这会导致 Pinned Header 在滚动时出现抖动。

为了解决这个问题,您可以使用以下方法:

  1. 使用 CustomScrollView 代替 NestedScrollView。
  2. 在 CustomScrollView 中使用 SliverAppBar 代替 Pinned Header。
  3. 在 CustomScrollView 中使用 SliverList 代替 ListView 或 GridView。
  4. 在 CustomScrollView 中使用 SliverPersistentHeader 代替 Pinned Header。

通过使用这些方法,您可以避免在 NestedScrollView 中使用 Pinned Header,从而解决滚动抖动的问题。

现在,让我们来看一个具体的例子。假设您有一个包含 Pinned Header 的 NestedScrollView。您可以使用以下代码将其替换为一个使用 CustomScrollView 和 SliverAppBar 的解决方案:

CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      pinned: true,
      title: Text('Pinned Header'),
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) => ListTile(
          title: Text('Item $index'),
        ),
        childCount: 100,
      ),
    ),
  ],
)

这样,您就可以在 NestedScrollView 中使用 Pinned Header,而不会遇到滚动抖动的问题了。

希望这篇博文对您有所帮助!如果您有任何问题,请随时留言。