实现平滑过渡,让显示更流畅,而不是生硬的突然出现和消失。
以下是一个示例
// 如果使用的脚手架,extendBodyBehindAppBar需要设置为true才能透明body的内容
// 如果未使用脚手架的appBar属性,忽略本小段
Scaffold(
appBar: 你的appbar,
extendBodyBehindAppBar: true,
)
// state中定义的变量,我使用的是getx,根据自己实际情况定义
bool showAppBar = false;
double appBarOpacity = 0.0;
// 使用这个widget滑动监听组件包裹你的列表
NotificationListener<ScrollNotification>(
onNotification: onNotification,
child: ListView()
)
// NotificationListener的onNotification回调监听
bool onNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification) {
double scrollOffset = notification.metrics.pixels;
final show = scrollOffset > 50.w;
// 展示或隐藏appbar
if (show != state.showAppBar) {
state.showAppBar = show;
}
// 从滑动距离达到50开始,达到110结束,appBarOpacity赋值到appbar的背景色
colorOpacity(scrollOffset, 50.w, 110.w, (opt) {
state.appBarOpacity = opt;
});
update();
}
return false;
}
// 平滑过渡值计算
void colorOpacity(double offset,double startOffset,double endOffset,Function(double) callback){
double opt = 1;
if (offset <= startOffset) {
opt = 0; // 未达到起始位置,完全透明
} else if (offset >= endOffset) {
opt = 1; // 超过结束位置,完全不透明
} else {
// 中间区间:线性计算透明度(0~1之间平滑过渡)
opt = (offset - startOffset) / (endOffset - startOffset);
}
callback(opt);
}
以下是往上滑动的效果,部分截图