flutter_swiper插件的分页指示器默认只有SwiperPagination.dots(圆点)和SwiperPagination.fraction(数字)两种显示效果,现需做成类似于拼多多这样
处理步骤:
1.找到插件中指示器部分的源码,并复制到项目组件文件夹下
2.flutter_page_indicator.dart文件修改如下
新增LinePainter和LineBasePainter两个类
LinePainter:
class LinePainter extends LineBasePainter {
LinePainter(PageIndicator widget, double page, int index, Paint paint)
: super(widget, page, index, paint);
@override
void draw(Canvas canvas, double space, double size, double radius) {
double secondOffset = index == widget.count - 1
? radius
: radius + ((index + 1) * (size + space));
// _paint.color = AppColors.app_main;
_paint.color = Colors.grey[350];
_paint.strokeWidth = 3;
canvas.drawLine(new Offset(secondOffset - 3, radius),
new Offset(secondOffset + 8, radius), _paint);
}
}
3.LineBasePainter:
abstract class LineBasePainter extends BasePainter {
final PageIndicator widget;
final double page;
final int index;
final Paint _paint;
double lerp(double begin, double end, double progress) {
return begin + (end - begin) * progress;
}
LineBasePainter(this.widget, this.page, this.index, this._paint)
: super(widget, page, index, _paint);
void draw(Canvas canvas, double space, double size, double radius);
bool _shouldSkip(int index) {
return false;
}
//double secondOffset = index == widget.count-1 ? radius : radius + ((index + 1) * (size + space));
@override
void paint(Canvas canvas, Size size) {
_paint.color = widget.color;
double space = widget.space;
double size = widget.size;
double radius = size / 2;
for (int i = 0, c = widget.count; i < c; ++i) {
if (_shouldSkip(i)) {
continue;
}
canvas.drawLine(new Offset(i * (size + space) + radius - 3, radius),
new Offset(i * (size + space) + radius + 8, radius), _paint);
}
double page = this.page;
if (page < index) {
page = 0.0;
}
_paint.color = widget.activeColor;
draw(canvas, space, size, radius);
}
@override
bool shouldRepaint(BasePainter oldDelegate) {
return oldDelegate.page != page;
}
}
4.新增横线类型枚举
enum PageIndicatorLayout {
NONE,
SLIDE,
WARM,
COLOR,
SCALE,
DROP,
LINE, // 横线类型
}
5.在_PageIndicatorState的_createPainer方法中新增:
BasePainter _createPainer() {
switch (widget.layout) {
case PageIndicatorLayout.LINE:
return new LinePainter(
widget, widget.controller.page ?? 0.0, index, _paint);
case PageIndicatorLayout.NONE:
....
}
}
6.最后项目中使用:
引入该文件
import 'package:flutter_app/component/flutter_page_indicator-0.0.3/lib/flutter_page_indicator.dart';
轮播部分代码
Swiper(
itemCount: 2,
pagination: SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
return Container(
alignment: Alignment.bottomCenter,
height: AppSize.height(Theme.of(context).platform == TargetPlatform.iOS ? 300: 280),
child: PageIndicator(
layout: PageIndicatorLayout.LINE,
size: 10,
space: 0,
count: 2,
controller: config.pageController,
color: Colors.redAccent,
),
);
}),
autoplay: false,
index: 0,
效果如下:
参考博客:https://www.jianshu.com/p/d4b406bca164