Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating SliverAppBar or AppBar = Changing background color while scrolling

Is it possible to change the background of Appbar or SliverAppbar while scrolling?. I have these requirements for a SliverAppbar or Appbar and I don't find a way to solve them.

  • At the first page, the Appbar or SliverAppBar didn't have a background color or transparent.
  • When scrolling the page the Appbar or SliverAppBar changing from didn't have a background color to have a background color.

This the first appearance of the Appbar or SliverAppbar

This the AppBar or SliverAppbar appearance when scrolled

Here the example that i want to achieve

Here the example that i want to achieve

like image 409
ezra Rahardian Avatar asked Oct 17 '25 10:10

ezra Rahardian


1 Answers

Method 1:

If you want to use FlexibleSpaceBar you can specify a background color for it, and when the app bar is expanded, you will see the FlexibleSpaceBar's background color. For example:

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

Method 2:

If you don't want to use FlexibleSpaceBar (or if you don't want to expand/stretch the AppBar), you can use SliverLayoutBuilder to check whether scrolling has occurred. If constraints.scrollOffset > 0, that means the user has scrolled at least a little bit. For example:

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

Using this method, if you want to do some transition when scrolling, it's easy too - just get the current scrollOffset and generate a color based on that.

like image 136
user1032613 Avatar answered Oct 20 '25 00:10

user1032613