Flutter中滑动Card时显示的按钮自定义方案
解决方案
修改 MatchCard 组件代码
// lib/widgets/match_card.dart import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import '../models/match_record.dart'; class MatchCard extends StatelessWidget { final MatchRecord record; final VoidCallback? onShare; final VoidCallback? onRemove; const MatchCard({Key? key, required this.record, this.onShare, this.onRemove}) : super(key: key); String _formatDate(DateTime date) { return DateFormat.yMMMd().format(date); } @override Widget build(BuildContext context) { // 将Card的margin移到Slidable外层,保证Slidable高度与Card完全匹配 return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Slidable( key: ValueKey(record.date.toString()), endActionPane: ActionPane( motion: const ScrollMotion(), extentRatio: 0.3, children: [ Expanded( child: Column( children: [ // 分享按钮,占满上方区域 Expanded( child: SlidableAction( onPressed: (context) => onShare?.call(), backgroundColor: Colors.blue, foregroundColor: Colors.white, icon: Icons.share, ), ), // 按钮间的垂直间距 const SizedBox(height: 4), // 删除按钮,占满下方区域 Expanded( child: SlidableAction( onPressed: (context) => onRemove?.call(), backgroundColor: Colors.red, foregroundColor: Colors.white, icon: Icons.delete, ), ), ], ), ), ], ), child: SizedBox( width: double.infinity, child: Card( margin: EdgeInsets.zero, // 移除Card自身的margin elevation: 4, child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Team 1: ${record.team1.join(' & ')}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 4), Text( 'Team 2: ${record.team2.join(' & ')}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Text('Score: ${record.score}', style: const TextStyle(fontSize: 14)), const SizedBox(height: 8), Text('Date: ${_formatDate(record.date)}', style: TextStyle(fontSize: 12, color: Colors.grey[600])), ], ), ), ), ), ), ); } }
完善 MatchRecordsPage 的按钮回调
确保按钮点击能触发对应逻辑,修改页面中的itemBuilder:
// lib/screens/match_records_page.dart // ...(其他代码不变) body: ListView.builder( itemCount: records.length, itemBuilder: (context, index) { return MatchCard( record: records[index], onShare: () { // 替换为你的分享逻辑 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('执行分享操作'))); }, onRemove: () { // 替换为你的删除逻辑 setState(() { records.removeAt(index); }); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('记录已删除'))); }, ); }, ), // ...(其他代码不变)
修改说明
匹配Card高度:
- 把原本Card的
margin转移到Slidable外层的Padding组件中,同时将Card的margin设为EdgeInsets.zero,这样Slidable的高度就和Card完全一致,ActionPane内的按钮高度自然匹配Card。
- 把原本Card的
添加按钮垂直间距:
- 将ActionPane的子组件改为垂直布局的
Column,用Expanded让两个按钮平分可用高度,中间通过SizedBox(height:4)设置垂直间距,既保证按钮填满对应区域,又实现了间距需求。
- 将ActionPane的子组件改为垂直布局的
内容的提问来源于stack exchange,提问作者snu
相关产品推荐
相关产品推荐

