I am working on a Flutter Application in which I have the following behaviour –
We have a appbar and a carousel slider component. I want to achieve a behaviour where the Sliver App var consists of the actual Appbar in title (logo, action items) and below it we have the horizontal scroll able banner component. When the page is scrolled, the banner component disappears and the appbar sticks to the top. In expanded state, the whole sliver app bar has a common gradient applied to it. When scrolled and appbar is collapsed, the color changes to a solid color.
How can we achieve such a behavior?
My code is-
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: CustomScrollView(
slivers: [
SliverAppBar(
title: AppBar(
title: const Text("Sliver AppBar with Carousel"),
backgroundColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
elevation: 0,
automaticallyImplyLeading: false,
),
titleSpacing: 0,
centerTitle: false,
backgroundColor: Colors.white,
surfaceTintColor: Colors.white,
expandedHeight: 112 + 38 + kToolbarHeight,
pinned: true,
floating: false,
flexibleSpace: FlexibleSpaceBar(
background: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.blue,
Colors.white,
],
stops: [
0,
0.65,
],
),
),
child: Column(
children: [
const SizedBox(
height: 38 + kToolbarHeight,
),
CarouselSlider(
items: [
Container(
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(
color: Colors.red,
),
),
height: 112,
child: const Center(
child: Text('Item 1'),
),
),
Container(
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(
color: Colors.red,
),
),
height: 112,
child: const Center(
child: Text('Item 2'),
),
),
Container(
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(
color: Colors.red,
),
),
height: 112,
child: const Center(
child: Text('Item 3'),
),
),
],
options: CarouselOptions(
height: 112.0,
autoPlay: true,
enlargeCenterPage: true,
aspectRatio: 16 / 9,
viewportFraction: 1.0,
),
),
],
),
)),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return ListTile(
title: Text('Item #$index'),
);
},
childCount: 20,
),
),
],
),
);
}
}
The above code gives following behavior-
Collapsed height-
Note– Hardcoding the blue color as the background color, causes a 1px thin blue colored line to appear below the appbar. To avoid this, I am using the background color as white by default.
2