先看效果:

滾動(dòng)出現(xiàn)appBar
實(shí)現(xiàn):
這邊主要是用到了NotificationListener這個(gè)widget,借助這個(gè)widget可以監(jiān)聽(tīng)滾動(dòng)的高度。appBar則使用自定義widget實(shí)現(xiàn),給外層嵌套一個(gè)opacity組件,通過(guò)滾動(dòng)監(jiān)聽(tīng)高度變化然后改變appBar透明度即可。
NotificationListener(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollUpdateNotification) {
_onScroll(scrollNotification.metrics.pixels);
}
}
判斷條件里的ScrollUpdateNotification是指widget組件位置發(fā)生改變才會(huì)執(zhí)行相應(yīng)的邏輯
_onScroll函數(shù)方法實(shí)現(xiàn):
_onScroll (offset) {
double alpha = offset / APPBAE_SCROLL_OFFSET; // APPBAE_SCROLL_OFFSET為appBar高度
if (alpha < 0) {
alpha = 0;
} else if (alpha > 1) {
alpha = 1;
}
setState(() {
alphaAppBar = alpha;
});
}
完整示例代碼:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter_swiper/flutter_swiper.dart';
const APPBAE_SCROLL_OFFSET = 100;
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List _imageUrl = [
'https://wx1.sinaimg.cn/mw690/684e58a1gy1g56ma49gxtj22c02xvb2b.jpg',
'https://wx2.sinaimg.cn/mw690/6a0576a9ly1g2d262s749j24s036okjs.jpg',
];
double alphaAppBar = 1;
@override
void initState() {
super.initState();
}
_onScroll (offset) {
double alpha = offset / APPBAE_SCROLL_OFFSET;
if (alpha < 0) {
alpha = 0;
} else if (alpha > 1) {
alpha = 1;
}
setState(() {
alphaAppBar = alpha;
});
print(alphaAppBar);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xfff2f2f2),
body: Stack(
children: <Widget>[
MediaQuery.removePadding(
removeTop: true,
context: context,
child: NotificationListener(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollUpdateNotification) {
_onScroll(scrollNotification.metrics.pixels);
}
return false;
},
child: ListView(
children: <Widget>[
Container(
height: 260,
child: Swiper(
itemCount: _imageUrl.length,
autoplay: true,
itemBuilder: (BuildContext, int index) {
return Image.network(
_imageUrl[index],
fit: BoxFit.fill,
);
},
pagination: SwiperPagination(),
),
),
Container(
height: 800,
)
],
)
)
),
Opacity(
opacity: alphaAppBar,
child: Container(
height: 80,
decoration: BoxDecoration(color: Colors.white),
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 20),
child: Text('首頁(yè)'),
),
),
),
)
],
)
);
}
}
關(guān)于更多使用NotificationListener的方法或例子,可以查看這里