Flutter 实现ListTile右向左水平拖拽时显示额外操作图标功能
要实现ListTile从右向左拖拽显示操作图标的效果,推荐使用Flutter生态成熟的flutter_slidable组件,原生ListTile本身没有内置滑动显隐组件的能力,用该组件可以快速匹配你要的交互效果。
实现步骤
- 先在项目的
pubspec.yaml文件中添加依赖:
dependencies: flutter: sdk: flutter # 添加下面这行,版本可替换为当前最新稳定版 flutter_slidable: ^3.1.0
添加后执行flutter pub get安装依赖。
- 替换你现有的代码结构,将ListTile包裹在Slidable组件内,原本放在trailing的操作按钮移动到滑动面板配置项中即可:
return Slidable( // 配置从右向左滑动呼出的面板 endActionPane: ActionPane( // 滑动动画效果,可选DrawerMotion、BehindMotion等,和抽屉式滑出效果匹配 motion: const DrawerMotion(), children: [ SlidableAction( onPressed: (context) {}, icon: Icons.favorite_border, backgroundColor: Colors.transparent, foregroundColor: Colors.black, ), SlidableAction( onPressed: (context) {}, icon: Icons.edit, backgroundColor: Colors.transparent, foregroundColor: Colors.black, ), SlidableAction( onPressed: (context) {}, icon: Icons.delete, backgroundColor: Colors.transparent, foregroundColor: Colors.black, ), ], ), child: ListTile( contentPadding: const EdgeInsets.all(5), onTap: () {}, onLongPress: () {}, horizontalTitleGap: 10, minVerticalPadding: 15, leading: CircleAvatar( radius: 34, child: Text( account['Name']!.substring(0, 1), style: const TextStyle(fontSize: 34, fontWeight: FontWeight.bold), ), ), title: Text( account['Name']!, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), subtitle: FittedBox( alignment: Alignment.centerLeft, fit: BoxFit.scaleDown, child: Text(account['Email']!) ), // 正常状态下trailing可以留空或者放其他固定展示的组件 ), );
如果不想引入第三方依赖,也可以自行通过GestureDetector监听水平拖拽偏移量,配合AnimatedContainer动态控制trailing区域的宽度和组件显隐,不过需要自行处理拖拽临界值、滑动阻尼、回弹动画等逻辑,适配成本更高,更推荐直接使用成熟的第三方组件。
内容的提问来源于stack exchange,提问作者al-ghaly
相关产品推荐
相关产品推荐

