如何在Flutter中实现图片所示的Stepper组件?
自定义Stepper组件实现方案
自带的Stepper组件样式固定,第三方库也未必完全匹配你的设计,直接自定义一个最灵活。以下是匹配你设计图的实现代码:
核心实现代码
1. 单个步骤组件 StepItem
负责渲染单个步骤的圆圈、数字和文字,处理激活状态的样式变化:
class StepItem extends StatelessWidget { final int index; final String title; final bool isActive; final bool isLast; final double lineWidth; const StepItem({ super.key, required this.index, required this.title, required this.isActive, required this.isLast, this.lineWidth = 40, }); @override Widget build(BuildContext context) { return Column( children: [ // 步骤圆圈 + 连接线 Row( children: [ // 步骤圆圈 Container( width: 32, height: 32, decoration: BoxDecoration( color: isActive ? const Color(0xFF007AFF) : Colors.white, border: Border.all( color: const Color(0xFF007AFF), width: 2, ), borderRadius: BorderRadius.circular(16), ), child: Center( child: Text( '$index', style: TextStyle( color: isActive ? Colors.white : const Color(0xFF007AFF), fontWeight: FontWeight.bold, fontSize: 16, ), ), ), ), // 连接线(最后一个步骤不显示) if (!isLast) Container( width: lineWidth, height: 2, color: isActive ? const Color(0xFF007AFF) : const Color(0xFFE0E0E0), ), ], ), const SizedBox(height: 8), // 步骤标题 Text( title, style: TextStyle( color: isActive ? const Color(0xFF007AFF) : const Color(0xFF8E8E93), fontSize: 12, ), ), ], ); } }
2. 整合所有步骤的父组件 CustomStepper
管理当前激活的步骤,将多个StepItem组合并自适应布局:
class CustomStepper extends StatelessWidget { final int currentStep; final List<String> stepTitles; const CustomStepper({ super.key, required this.currentStep, required this.stepTitles, }); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: List.generate(stepTitles.length, (index) { final stepIndex = index + 1; return StepItem( index: stepIndex, title: stepTitles[index], isActive: stepIndex <= currentStep, isLast: index == stepTitles.length - 1, // 动态计算连接线宽度,让步骤均匀分布 lineWidth: (MediaQuery.of(context).size.width - (32 * stepTitles.length)) / (stepTitles.length - 1) - 16, ); }), ); } }
3. 使用示例
在页面中直接调用,传入当前步骤和步骤标题即可:
class StepperDemo extends StatelessWidget { const StepperDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('自定义Stepper示例')), body: Padding( padding: const EdgeInsets.all(20.0), child: CustomStepper( currentStep: 1, // 当前激活第1步 stepTitles: const ['Step 1', 'Step 2', 'Step 3'], ), ), ); } }
样式调整说明
- 颜色:修改
Color(0xFF007AFF)(蓝色)和Color(0xFFE0E0E0)(灰色)可匹配你的设计色值 - 圆圈大小:调整
StepItem里的width:32和height:32参数 - 连接线长度:
CustomStepper已做自适应布局,也可手动替换固定数值 - 文字样式:修改
Text的fontSize、fontWeight等属性调整排版
内容的提问来源于stack exchange,提问作者Umer Yaseen
相关产品推荐
相关产品推荐

