如何让LinearPercentIndicator的widgetIndicator居中显示
LinearPercentIndicator的widgetIndicator居中解决方案
问题背景
使用percent_indicator: ^4.2.2的LinearPercentIndicator组件时,widgetIndicator属性传入的自定义指示器无法在进度条对应位置居中,表现为数字指示器偏右、未对齐进度条垂直中线。查看源码可知组件内部通过Positioned直接将指示器左上角对齐到进度百分比对应的坐标点,未做居中偏移计算。
原始问题代码:
LinearPercentIndicator( animateFromLastPercent: true, width: MediaQuery.of(context).size.width, animation: true, lineHeight: 20.0, animationDuration: 600, percent: valueIndicator == 0 ? 1 / allCards!.length * (indexCard + 1) : valueIndicator, widgetIndicator: Text( '${indexCard + 1}', style: const TextStyle(fontWeight: FontWeight.bold), ), barRadius: const Radius.circular(10), curve: Curves.decelerate, progressColor: AppTheme.darkP3, backgroundColor: AppTheme.darkP2, )
可行方案
方案1:Transform.translate偏移修正(推荐,无侵入)
Positioned默认对齐的是指示器组件的左上角,只需要给widgetIndicator外层包一层Transform.translate,根据指示器自身尺寸做反向偏移即可实现居中:
- 水平方向:向左偏移指示器自身宽度的1/2,让组件中心点对齐进度坐标点
- 垂直方向:根据进度条高度和指示器高度的差值,偏移对应距离让组件垂直居中
修正后代码:
// 预先定义指示器尺寸,可根据实际样式调整 const double indicatorW = 24; const double indicatorH = 24; const double lineHeight = 20; LinearPercentIndicator( animateFromLastPercent: true, width: MediaQuery.of(context).size.width, animation: true, lineHeight: lineHeight, animationDuration: 600, percent: valueIndicator == 0 ? 1 / allCards!.length * (indexCard + 1) : valueIndicator, widgetIndicator: Transform.translate( // 计算偏移量 offset: Offset(-indicatorW / 2, (lineHeight - indicatorH) / 2), child: Container( width: indicatorW, height: indicatorH, alignment: Alignment.center, child: Text( '${indexCard + 1}', style: const TextStyle(fontWeight: FontWeight.bold), ), ), ), barRadius: const Radius.circular(10), curve: Curves.decelerate, progressColor: AppTheme.darkP3, backgroundColor: AppTheme.darkP2, )
如果指示器尺寸不固定,可以通过
GlobalKey获取组件渲染后的真实宽高,动态计算偏移值即可。
方案2:修改组件源码定位逻辑
如果项目中多处用到该组件,不想重复写偏移逻辑,可以直接修改组件源码:
- 进入pub缓存目录,打开
percent_indicator-4.2.2/lib/src/linear_percent_indicator.dart文件 - 找到
widgetIndicator对应的Positioned布局代码,原逻辑直接将left设置为percent * width - 新增指示器宽高获取逻辑,将
left值减去指示器宽度的1/2,top值设置为(lineHeight - 指示器高度)/2即可
该方案缺点是更新依赖、重新拉取包时修改会丢失,建议将修改后的包源码放到本地目录,通过本地路径引用依赖。
方案3:使用trailing属性放置固定指示器
如果指示器不需要跟随进度动画移动,仅需要固定在进度条末端,可以直接将指示器放到LinearPercentIndicator的trailing属性中,通过padding调整位置即可,该方案仅适用固定位置场景。
内容的提问来源于stack exchange,提问作者Waldson Fagundes
相关产品推荐
相关产品推荐

