smooth_star_rating.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import 'package:flutter/material.dart';
  2. typedef void RatingChangeCallback(double rating);
  3. class SmoothStarRating extends StatelessWidget {
  4. final double paddingLeft;
  5. final double paddingRight;
  6. final int starCount;
  7. final double rating;
  8. final RatingChangeCallback onRatingChanged;
  9. final Color color;
  10. final Color borderColor;
  11. final double size;
  12. final bool allowHalfRating;
  13. Widget iconNormal;
  14. Widget iconSelected;
  15. SmoothStarRating(
  16. {
  17. this.starCount = 5,
  18. this.paddingLeft = 5.0,
  19. this.paddingRight = 5.0,
  20. this.rating = 0.0,
  21. this.onRatingChanged,
  22. this.color,
  23. this.borderColor,
  24. this.size,
  25. this.allowHalfRating = true,
  26. this.iconNormal,
  27. this.iconSelected}) {
  28. assert(this.rating != null);
  29. }
  30. Widget buildStar(BuildContext context, int index) {
  31. Widget iconWidget;
  32. if (index >= rating) {
  33. // icon = new Icon(
  34. // Icons.star_border,
  35. // color: borderColor ?? Theme.of(context).primaryColor,
  36. // size: size ?? 25.0,
  37. // );
  38. iconWidget = iconNormal;
  39. } else if (index > rating - (allowHalfRating ? 0.5 : 1.0) &&
  40. index < rating) {
  41. // icon = new Icon(
  42. // Icons.star_half,
  43. // color: color ?? Theme.of(context).primaryColor,
  44. // size: size ?? 25.0,
  45. // );
  46. } else {
  47. // icon = new Icon(
  48. // Icons.star,
  49. // color: color ?? Theme.of(context).primaryColor,
  50. // size: size ?? 25.0,
  51. // );
  52. iconWidget = iconSelected;
  53. }
  54. return new GestureDetector(
  55. onTap: () {
  56. if (this.onRatingChanged != null) onRatingChanged(index + 1.0);
  57. },
  58. onHorizontalDragUpdate: (dragDetails) {
  59. RenderBox box = context.findRenderObject();
  60. var _pos = box.globalToLocal(dragDetails.globalPosition);
  61. var i = _pos.dx / size;
  62. var newRating = allowHalfRating ? i : i.round().toDouble();
  63. if (newRating > starCount) {
  64. newRating = starCount.toDouble();
  65. }
  66. if (newRating < 0) {
  67. newRating = 0.0;
  68. }
  69. if (this.onRatingChanged != null) onRatingChanged(newRating);
  70. },
  71. child:Container(
  72. padding: EdgeInsets.only(left: paddingLeft,right: paddingRight),
  73. child: iconWidget,
  74. ),
  75. );
  76. }
  77. @override
  78. Widget build(BuildContext context) {
  79. return new Material(
  80. color: Colors.transparent,
  81. child: new Wrap(
  82. alignment: WrapAlignment.start,
  83. children: new List.generate(
  84. starCount, (index) => buildStar(context, index))),
  85. );
  86. }
  87. }