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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With