使用 Flutter 进行自定义控件
学习使用Flutter 自定义 五星评价 展示控件
// 星星评分展示
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; // 未选中Imagefinal Widget selectedImages; // 选中ImagestarRating({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、 创建 startsList<Widget> stars = [];var selectedColor;final star = widget.selectedImages;// 2、 构建 满星 startdouble oneValue = widget.maxRating / widget.count;int entireCount = (widget.rating / oneValue).floor();for (int i = 0; i < entireCount; i++) {stars.add(star);}// 3、构建部分填充stardouble 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 五星评价展示控件,目前只是用于展示,并没有添加任何交互功能,后续进行交互完善。