前言
再蛮多的项目中,不喜欢一开始页面中就出现appBar,而当我们拉到一定的高度之后,appBar才会出现—这个就是渐变appBar
实现效果展示
实例代码分析
1.状态监听(监听滑动的高度)
NotificationListener( //状态监听
onNotification: (notification){
//如果是滚动更新通知的值并且深度限制为0[就是监听ListView]
if(notification is ScrollUpdateNotification && notification.depth==0){
//如果是
_onScrol(notification.metrics.pixels);
}
},
)
2.控制透明度的改变
const maxOffset=100; //最高的高度
double opacityValue=0;
void _onScrol(offset){
double alpha=offset/maxOffset;
if(alpha<0){
alpha=0;
}else if(alpha>1){
alpha=1;
}
setState(() {
opacityValue=alpha;
});
//print(offset);
}
全部代码
import 'package:flutter/material.dart';
class GradientDemo extends StatefulWidget {
GradientDemo({Key key}) : super(key: key);
_GradientDemoState createState() => _GradientDemoState();
}
const maxOffset=100;
class _GradientDemoState extends State<GradientDemo> {
double opacityValue=0;
void _onScrol(offset){
double alpha=offset/maxOffset;
if(alpha<0){
alpha=0;
}else if(alpha>1){
alpha=1;
}
setState(() {
opacityValue=alpha;
});
//print(offset);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
MediaQuery.removePadding(
removeTop: true,
context: context,
child: NotificationListener( //状态监听
onNotification: (notification){
//如果是滚动更新通知的值并且深度限制为0[就是监听ListView]
if(notification is ScrollUpdateNotification && notification.depth==0){
//如果是
_onScrol(notification.metrics.pixels);
}
},
child: ListView(
children: <Widget>[
Image.network('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1562324532571&di=80a74e17231e47372ad4cacda1926230&imgtype=0&src=http%3A%2F%2Fphotos.tuchong.com%2F414540%2Ff%2F27530238.jpg',height: 180,fit: BoxFit.cover,),
Container(
height: 800,
child: Text(
'渐变appBar',
style: Theme.of(context).textTheme.display2
,
),
)
],
),
)
),
Opacity(
opacity: opacityValue,
child: Container(
height: 80,
child: AppBar(
title: Text('渐变AppBar'),
centerTitle: true,
),
),
)
],
)
);
}
}