1.XFDashedLine效果展示
目的:實現(xiàn)效果的同時匾二,提供定制,并且可以實現(xiàn)水平和垂直兩種虛線效果:
- axis:確定虛線的方向嚼锄;
- dashedWidth:根據(jù)虛線的方向確定自己虛線的寬度;
- dashedHeight:根據(jù)虛線的方向確定自己虛線的高度;
- count:內(nèi)部會根據(jù)設(shè)置的個數(shù)和寬高確定密度(虛線的空白間隔)煤傍;
- color:虛線的顏色
暫時實現(xiàn)上面的定制,后續(xù)有新的需求繼續(xù)添加新的功能點~
2. 實現(xiàn)思路分析
實現(xiàn)比較簡單嘱蛋,主要是根據(jù)用戶傳入的方向確定添加對應(yīng)的SizedBox即可蚯姆。
這里有一個注意點:虛線到底是設(shè)置多寬或者多高呢?
- 我這里是根據(jù)方向獲取父Widget的寬度和高度來決定的洒敏;
- 通過LayoutBuilder可以獲取到父Widget的寬度和高度龄恋;
return LayoutBuilder(
builder:(BuildContext context,BoxConstraints constraints){
//根據(jù)寬度計算個數(shù)
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代碼實現(xiàn)
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){
//根據(jù)寬度計算個數(shù)
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,
)
),
],
),
學(xué)習(xí)內(nèi)容來自Flutter從入門到實戰(zhàn)