flutter 滚动监听
本文最后更新于:2022年4月22日 上午
flutter 滚动监听
ScrollController
- 先创建一个
ScrollController
- 然后在
initState
中监听滚动 - 在
ListView
或者GridView
中的controller
中将其传入 - 在
dispose
中取消监听
在 _scrollController.offset
中可以获取到当前滚动的距离
在 _scrollController.animateTo
可以滚动到指定距离
class HomePage extends StatefulWidget {
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// 监听滚动,初始化滚动距离
final ScrollController _scrollController = ScrollController(initialScrollOffset: 200);
bool showTop = false;
@override
void initState() {
super.initState();
_scrollController.addListener(() {
print('开始滚动, 当前滚动距离${_scrollController.offset}');
});
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.builder(
itemCount: 100,
controller: _scrollController,
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 100, mainAxisSpacing: 5, crossAxisSpacing: 5),
itemBuilder: (BuildContext context, index) {
return Container(
width: 100,
height: 100,
color: Color.fromRGBO(
Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), Random().nextInt(10) / 10),
);
},
),
floatingActionButton: showTop
? FloatingActionButton(
child: Icon(Icons.vertical_align_top),
onPressed: () {
// 回到顶部
_scrollController.animateTo(0, duration: Duration(milliseconds: 600), curve: Curves.ease);
},
)
: null,
);
}
floatingActionButton
floatingActionButton
为屏幕右下角的位置按钮
NotificationListener
NotificationListener
的方式和 ScrollController
不太一样
NotificationListener
为在onNotification
中监听不同的事件来做不同的判断,
return NotificationListener(
onNotification: (ScrollNotification scrollNotification) {
// 通过 is 关键字来判断所属类
if (scrollNotification is ScrollStartNotification) {
print('开始滚动');
} else if (scrollNotification is ScrollUpdateNotification) {
print('滚动中 当前滚动: ${scrollNotification.metrics.pixels}');
} else if (scrollNotification is ScrollEndNotification) {
print('结束滚动');
}
return true;
},
child: GridView.builder(
itemCount: 100,
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 100, mainAxisSpacing: 5, crossAxisSpacing: 5),
itemBuilder: (BuildContext context, index) {
return Container(
width: 100,
height: 100,
color: Color.fromRGBO(
Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), Random().nextInt(10) / 10),
);
},
),
);
is
操作符
is
操作符为校验不同的类型
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议,转载请注明出处。