动画 SliverAppBar 或 AppBar = 滚动时改变背景颜色

Animating SliverAppBar or AppBar = Changing background color while scrolling

是否可以在滚动时更改Appbar或SliverAppbar的背景?. 我对 SliverAppbarAppbar 有这些要求,但我找不到解决它们的方法。

This the first appearance of the Appbar or SliverAppbar

This the AppBar or SliverAppbar appearance when scrolled

这里是我想要实现的例子

方法一:

如果你想使用FlexibleSpaceBar,你可以为它指定一个背景颜色,当应用栏展开时,你会看到FlexibleSpaceBar的背景颜色。例如:

      SliverAppBar(
        backgroundColor: Colors.blue,
        expandedHeight: 200,
        pinned: true,
        flexibleSpace: FlexibleSpaceBar(
          background: Container(
            color: Colors.red,
          ),
        ),
      )

方法二:

如果你不想使用FlexibleSpaceBar(或者如果你不想expand/stretch AppBar),你可以使用SliverLayoutBuilder来检查是否发生滚动。如果 constraints.scrollOffset > 0,则表示用户至少滚动了一点点。例如:

      SliverLayoutBuilder(
        builder: (BuildContext context, constraints) {
          final scrolled = constraints.scrollOffset > 0;
          return SliverAppBar(
            backgroundColor: scrolled ? Colors.blue : Colors.red,
            pinned: true,
          );
        },
      )

使用此方法,如果您想在滚动时进行一些过渡,也很容易 - 只需获取当前 scrollOffset 并基于该颜色生成颜色即可。