Flutter 自定义AppBar实现滚动渐变
在Flutter中,可以通过NotificationListener
来监听ScrollNotification
,然后根据滚动的位置来更新AppBar
的样式。以下是一个简单的实例代码,演示了如何实现AppBar的滚动渐变效果:
import 'package:flutter/material.dart';
class ScrollGradientAppBar extends StatefulWidget {
@override
_ScrollGradientAppBarState createState() => _ScrollGradientAppBarState();
}
class _ScrollGradientAppBarState extends State<ScrollGradientAppBar> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<Color> _colorAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: Duration(milliseconds: 300));
_colorAnimation = ColorTween(begin: Colors.transparent, end: Colors.blue).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
if (notification is UserScrollNotification && notification.scrollDelta != null) {
if (notification.scrollDelta < 0) {
_controller.forward(); // Scroll up
} else {
_controller.reverse(); // Scroll down
}
}
return true;
},
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
expandedHeight: 200.0,
floating: false,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
background: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.center,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
_colorAnimation.value,
],
),
),
),
),
),
// ... other slivers
],
),
),
);
}
}
这段代码中,NotificationListener
用于监听ScrollNotification
,然后根据用户的滚动行为来控制动画控制器,从而更新渐变的颜色。SliverAppBar
的flexibleSpace
属性被用来显示带有渐变效果的背景。这里使用了LinearGradient
来实现渐变效果,并通过动画控制器来更改渐变的起始颜色,实现滚动时的颜色渐变效果。
评论已关闭