方案一:Controller
- 可以设置默认的offset;
- 监听滚动,也可以监听滚动的位置;
- 不能监听开始滚动、结束滚动;
class _YZHomePageState extends State<YZHomePage> {
ScrollController _controller_01 = ScrollController(initialScrollOffset: 300);
bool _isShowFloatingBtn = false;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller_01.addListener(() {
print("监听到滚动...${_controller_01.offset}");
_isShowFloatingBtn = _controller_01.offset >= 1000;
setState(() {
_isShowFloatingBtn = _controller_01.offset >= 1000;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("列表")
)
body: ListView.builder(
controller: _controller_01,
itemCount: 100,
itemBuilder: (BuildContext ctx, int index){
return ListTile(
leading: Icon(Icons.people),
title: Text("联系人$index"),
);
}),
floatingActionButton: _isShowFloatingBtn ? FloatingActionButton(
child: Icon(Icons.arrow_upward),
onPressed: () {
_controller_01.animateTo(0, duration: Duration(seconds: 1), curve: Curves.easeIn);
},
) : null,
);
}
}
方案二:NotificationListener
class _YZHomePageState extends State<YZHomePage> {
ScrollController _controller_01 = ScrollController(initialScrollOffset: 300);
bool _isShowFloatingBtn = false;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller_01.addListener(() {
// print("监听到滚动...${_controller_01.offset}");
setState(() {
_isShowFloatingBtn = _controller_01.offset >= 1000;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("列表")
),
body: NotificationListener(
onNotification: (ScrollNotification notification) {
if (notification is ScrollStartNotification) {
print("开始滚动");
} else if (notification is ScrollUpdateNotification) {
print("正在滚动。。。总滚动距离:${notification.metrics.maxScrollExtent}");
} else if (notification is ScrollEndNotification) {
print("结束滚动");
}
return true;
},
child: ListView.builder(
controller: _controller_01,
itemCount: 100,
itemBuilder: (BuildContext ctx, int index){
return ListTile(
leading: Icon(Icons.people),
title: Text("联系人$index"),
);
}),
),
floatingActionButton: _isShowFloatingBtn ? FloatingActionButton(
child: Icon(Icons.arrow_upward),
onPressed: () {
_controller_01.animateTo(0, duration: Duration(seconds: 1), curve: Curves.easeIn);
},
) : null,
);
}
}
网友评论