1.XFDashedLine效果展示
目的:实现效果的同时,提供定制,并且可以实现水平和垂直两种虚线效果:
- axis:确定虚线的方向;
- dashedWidth:根据虚线的方向确定自己虚线的宽度;
- dashedHeight:根据虚线的方向确定自己虚线的高度;
- count:内部会根据设置的个数和宽高确定密度(虚线的空白间隔);
- color:虚线的颜色
暂时实现上面的定制,后续有新的需求继续添加新的功能点~
2. 实现思路分析
实现比较简单,主要是根据用户传入的方向确定添加对应的SizedBox即可。
这里有一个注意点:虚线到底是设置多宽或者多高呢?
- 我这里是根据方向获取父Widget的宽度和高度来决定的;
- 通过LayoutBuilder可以获取到父Widget的宽度和高度;
return LayoutBuilder(
builder:(BuildContext context,BoxConstraints constraints){
//根据宽度计算个数
return Flex(
direction: this.axis,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(this.count, (int index){
return SizedBox(
width: dashedWidth,
height: dashedHeight,
child: DecoratedBox(
decoration: BoxDecoration(color: color),
),
);
}),
);
},
);
3. XFDashedLine代码实现
import 'package:flutter/material.dart';
class XFDashedLine extends StatelessWidget {
final Axis axis;
final double dashedWidth;
final double dashedHeight;
final int count;
final Color color;
XFDashedLine({
@required this.axis,
this.dashedWidth = 1,
this.dashedHeight = 1,
this.count,
this.color = const Color(0xffff0000)
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder:(BuildContext context,BoxConstraints constraints){
//根据宽度计算个数
return Flex(
direction: this.axis,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(this.count, (int index){
return SizedBox(
width: dashedWidth,
height: dashedHeight,
child: DecoratedBox(
decoration: BoxDecoration(color: color),
),
);
}),
);
},
);
}
}
使用代码:
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 400,
child: XFDashedLine(
axis: Axis.horizontal,
count: 8,
dashedWidth: 30,
dashedHeight: 2,
)
),
SizedBox(height: 50,),
Container(
height: 400,
child: XFDashedLine(
axis: Axis.vertical,
count: 10,
dashedWidth: 2,
dashedHeight: 30,
color: Colors.blue,
)
),
],
),
学习内容来自Flutter从入门到实战