如何在Flutter中实现如图所示的点状组件?
自定义Flutter点状指示器实现方案
不用依赖第三方包,自己写自定义组件就能完全匹配你要的效果,以下是实现代码:
class DotIndicator extends StatelessWidget { final int currentIndex; final int itemCount; final Color selectedFillColor; final Color borderColor; final double selectedDotSize; final double normalDotSize; final double dotSpacing; const DotIndicator({ super.key, required this.currentIndex, required this.itemCount, this.selectedFillColor = const Color(0xFF007AFF), this.borderColor = const Color(0xFFCCCCCC), this.selectedDotSize = 12.0, this.normalDotSize = 8.0, this.dotSpacing = 10.0, }); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate(itemCount, (index) { final isSelected = index == currentIndex; return Padding( padding: EdgeInsets.symmetric(horizontal: dotSpacing / 2), child: Container( width: isSelected ? selectedDotSize : normalDotSize, height: isSelected ? selectedDotSize : normalDotSize, decoration: BoxDecoration( shape: BoxShape.circle, color: isSelected ? selectedFillColor : Colors.transparent, border: Border.all( color: isSelected ? selectedFillColor : borderColor, width: isSelected ? 0 : 1.2, ), ), ), ); }), ); } }
使用示例
// 对应第一张图(选中第一个点) DotIndicator( currentIndex: 0, itemCount: 3, ) // 对应第二张图(选中中间点) DotIndicator( currentIndex: 1, itemCount: 3, ) // 对应第三张图(选中最后一个点) DotIndicator( currentIndex: 2, itemCount: 3, )
你可以根据需求调整颜色、大小、间距这些参数,完全复刻图中的样式。
内容的提问来源于stack exchange,提问作者code box
相关产品推荐
相关产品推荐

