Flutter中如何实现点击卡片添加边框颜色及切换选中状态
实现Flutter水平滚动卡片的选中边框切换功能
核心思路
通过维护一个选中索引状态,动态控制每个卡片的边框样式——仅当前选中索引对应的卡片显示有色边框,其余卡片边框设为透明,点击新卡片时更新选中索引即可完成切换。
完整实现代码
import 'package:flutter/material.dart'; class HorizontalCardSelector extends StatefulWidget { const HorizontalCardSelector({super.key}); @override State<HorizontalCardSelector> createState() => _HorizontalCardSelectorState(); } class _HorizontalCardSelectorState extends State<HorizontalCardSelector> { // 存储选中卡片的索引,初始-1表示未选中任何卡片 int selectedCardIndex = -1; // 卡片标题列表,可按需扩展内容 final List<String> cardTitles = ['Painting', 'Sculpture', 'Photography', 'Design']; final TextStyle artStyle = const TextStyle(fontSize: 16, fontWeight: FontWeight.w500); @override Widget build(BuildContext context) { return ListView( scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), // 动态生成所有卡片 children: List.generate(cardTitles.length, (index) { return GestureDetector( onTap: () { setState(() { // 点击时更新选中索引为当前卡片的index selectedCardIndex = index; }); }, child: Card( elevation: 5, margin: const EdgeInsets.only(right: 12), shape: RoundedRectangleBorder( side: BorderSide( // 对比索引判断是否显示有色边框 color: selectedCardIndex == index ? Colors.blue : Colors.transparent, width: 2.0, ), borderRadius: BorderRadius.circular(8.0), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), child: Center( child: Text( cardTitles[index], style: artStyle, ), ), ), ), ); }), ); } }
关键修改说明
- 动态生成卡片:用
List.generate遍历标题列表生成卡片,避免重复编写单卡片代码,方便后续扩展卡片数量。 - 状态统一管理:通过
selectedCardIndex集中控制选中状态,点击卡片时调用setState更新状态,触发UI重绘切换边框。 - 边框逻辑优化:每个卡片的边框颜色通过索引对比动态设置,选中时显示指定颜色(示例用蓝色,可替换为红色等任意颜色),未选中时为透明。
- 布局细节优化:添加
margin避免卡片拥挤,补充垂直padding让卡片内容更美观。
进阶扩展:不同卡片用不同选中颜色
如果需要给每个卡片设置专属的选中边框颜色,可修改为:
// 定义对应每个卡片的选中颜色列表 final List<Color> selectedColors = [Colors.blue, Colors.red, Colors.green, Colors.orange]; // 边框颜色判断替换为 color: selectedCardIndex == index ? selectedColors[index] : Colors.transparent,
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

