flutter - 如何处理 ListView 滚动方向
问题描述
我有一个项目的虚拟列表,我想在向上滑动方向显示一个浮动操作按钮并在向下方向隐藏它。我怎样才能实现这个功能?
class _MyHomePageState extends State<MyHomePage> {
bool upDirection = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Container(
child: Row(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: 100,
itemBuilder: (context,index){
return ListTile(
title: Text(index.toString()),
);
},
),
)
],
),
),
),
floatingActionButton:upDirection==true?FloatingActionButton(onPressed: (){},):Container() ,
);
}
}
解决方案
截屏:
您只需要一个NotificationListener.onNotification
回调:
NotificationListener<UserScrollNotification>(
onNotification: (notification) {
final ScrollDirection direction = notification.direction;
return true;
},
child: ListView.builder(
itemCount: 100,
itemBuilder: (_, i) => ListTile(title: Text('$i')),
),
)
完整代码:
bool _visible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: AnimatedOpacity(
duration: Duration(milliseconds: 400),
opacity: _visible ? 1 : 0,
child: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {},
),
),
body: NotificationListener<UserScrollNotification>(
onNotification: (notification) {
final ScrollDirection direction = notification.direction;
setState(() {
if (direction == ScrollDirection.reverse) {
_visible = false;
} else if (direction == ScrollDirection.forward) {
_visible = true;
}
});
return true;
},
child: ListView.builder(
itemCount: 100,
itemBuilder: (_, i) => ListTile(title: Text('$i')),
),
),
);
}
推荐阅读
- mongodb - 如何在 MongoDB Realm 中创建嵌套数组?
- javascript - 如何在 swal (SweetAlert) 中创建/激活垂直滚动条
- laravel - Ubuntu laravel 生产迁移不起作用
- asp.net-core - UseExceptionHandler 不处理所有异常
- linux - 进程是如何在处理器中创建的?
- python-3.x - 在 Python 算法中未执行 AND 语句
- angular - 如何从父组件调用非特定子组件中的方法
- c# - Azure Keyvault 根据环境获取值
- java - 在Java中实现具有继承类型的接口
- electron - Electron:不断出现“您需要一个新应用程序才能打开此”屏幕