使用 Flutter 进行自定义控件
学习使用Flutter 自定义 五星评价 展示控件文章来源:https://www.uudwc.com/A/3mxnn/
// 星星评分展示
class starRating extends StatefulWidget {
// 初始化一些参数
final double rating; // 当前分数
final double maxRating; // 满分
final int count; // 评分个数
final double size; // 评分大小
final Color unselectedColor; // 没有选中颜色
final Color selectedColor; // 选中颜色
final Widget unselectedImage; // 未选中Image
final Widget selectedImages; // 选中Image
starRating({
required this.rating,
this.maxRating = 10,
this.count = 5,
this.size = 30,
this.unselectedColor = const Color(0xffbbbbbb),
this.selectedColor = const Color(0xffff0000),
Widget? unselectedImage,
Widget? selectedImage,
}): unselectedImage = (unselectedImage ?? Icon(Icons.star_border, color: unselectedColor, size: size)) as Widget,
selectedImages = (selectedImage ?? Icon(Icons.star, color: selectedColor, size: size)) as Widget;
State<StatefulWidget> createState() {
return _starRatingState();
}
}
class _starRatingState extends State<starRating> {
Widget build(BuildContext context) {
return Center(
child: Stack(
children: [
Row(mainAxisSize: MainAxisSize.min, children: buildUnselectedStar()),
Row(mainAxisSize: MainAxisSize.min, children: buildSelectedStar())
],
),
);
}
// 没有选中的星星
List<Widget> buildUnselectedStar () {
return List.generate(widget.count, (index) {
return widget.unselectedImage;
});
}
// 选中的星星
List<Widget> buildSelectedStar () {
// 1、 创建 starts
List<Widget> stars = [];
var selectedColor;
final star = widget.selectedImages;
// 2、 构建 满星 start
double oneValue = widget.maxRating / widget.count;
int entireCount = (widget.rating / oneValue).floor();
for (int i = 0; i < entireCount; i++) {
stars.add(star);
}
// 3、构建部分填充star
double leftWidth = ((widget.rating / oneValue) - entireCount) * widget.size;
final halfStar = ClipRect(
clipper: StartClipper(leftWidth),
child: star,
);
stars.add(halfStar);
// 如果填写的星星超过个数时
if (stars.length > widget.count) {
return stars.sublist(0, widget.count);
}
return stars;
}
}
// 自定义裁剪
class StartClipper extends CustomClipper<Rect> {
double width;
StartClipper(this.width);
getClip(Size size) {
return Rect.fromLTRB(0, 0, width, size.height);
}
bool shouldReclip(StartClipper oldClipper) {
return oldClipper.width != this.width;
}
}
自定义flutter 五星评价展示控件,目前只是用于展示,并没有添加任何交互功能,后续进行交互完善。文章来源地址https://www.uudwc.com/A/3mxnn/