smooth_star_rating.dart 2.4 KB

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