Flutter如何自定义FilterChip的形状以实现期望的布局效果
解决方案
你需要为FilterChip组件配置shape(未选中状态形状)、selectedShape(选中状态形状)以及side(边框样式)属性来自定义外观,同时注意调整选中状态下的文字颜色适配选中背景。
修改后的FilterChipWidget完整代码
class FilterChipWidget extends StatefulWidget { final String chipName; const FilterChipWidget({Key? key, required this.chipName}) : super(key: key); @override _FilterChipWidgetState createState() => _FilterChipWidgetState(); } class _FilterChipWidgetState extends State<FilterChipWidget> { var _isSelected = false; @override Widget build(BuildContext context) { return FilterChip( showCheckmark: false, label: Text(widget.chipName), labelStyle: GoogleFonts.robotoSlab( fontStyle: FontStyle.normal, fontWeight: FontWeight.w400, fontSize: 13, // 选中时文字改为白色,未选中保持黑色 color: _isSelected ? Colors.white : Colors.black), selected: _isSelected, backgroundColor: fTextFieldColor, // 未选中状态形状配置,可自定义圆角数值 shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: const BorderSide(color: Colors.transparent), ), // 选中状态形状配置 selectedShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: const BorderSide(color: Colors.blueAccent, width: 1), ), onSelected: (isSelected) { setState(() { _isSelected = isSelected; }); }, selectedColor: Colors.blueAccent, // 调整Chip内边距适配布局 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), ); } }
如果需要实现特殊切角样式,可自定义ShapeBorder实现,示例如下:
class CustomChipShape extends ShapeBorder { final double cutSize; final Color borderColor; final double borderWidth; const CustomChipShape({ this.cutSize = 8, this.borderColor = Colors.transparent, this.borderWidth = 1, }); @override EdgeInsetsGeometry get dimensions => EdgeInsets.all(borderWidth); @override Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return getOuterPath(rect.deflate(borderWidth), textDirection: textDirection); } @override Path getOuterPath(Rect rect, {TextDirection? textDirection}) { final path = Path(); path.lineTo(rect.width - cutSize, 0); path.lineTo(rect.width, cutSize); path.lineTo(rect.width, rect.height - cutSize); path.lineTo(rect.width - cutSize, rect.height); path.lineTo(cutSize, rect.height); path.lineTo(0, rect.height - cutSize); path.lineTo(0, cutSize); path.close(); return path; } @override void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { final paint = Paint() ..color = borderColor ..style = PaintingStyle.stroke ..strokeWidth = borderWidth; canvas.drawPath(getOuterPath(rect), paint); } @override ShapeBorder scale(double t) { return CustomChipShape( cutSize: cutSize * t, borderColor: borderColor, borderWidth: borderWidth * t, ); } }
使用时直接将shape和selectedShape属性的值替换为CustomChipShape()即可,可自行调整cutSize、边框颜色宽度等参数匹配设计需求。
优化提示
- 如需统一所有Chip高度,可给Text组件设置
maxLines: 1避免文本换行撑开高度 - 可调整Wrap组件的
runSpacing和spacing数值,匹配设计的Chip间距要求
内容的提问来源于stack exchange,提问作者user12790690
相关产品推荐
相关产品推荐

