Skip to content

Instantly share code, notes, and snippets.

@hleinone
Created August 20, 2018 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hleinone/a0b565d0593f77c6ec3b9c570c84bc7b to your computer and use it in GitHub Desktop.
Save hleinone/a0b565d0593f77c6ec3b9c570c84bc7b to your computer and use it in GitHub Desktop.
Flutter rating bar
import 'dart:math';
import 'package:flutter/material.dart';
class RatingBar extends StatelessWidget {
RatingBar({this.numStars = 5, this.rating = 0.0, this.onChanged});
final int numStars;
final double rating;
final ValueChanged<double> onChanged;
@override
Widget build(BuildContext context) {
return GestureDetector(
onHorizontalDragDown: (dragDown) {
RenderBox box = context.findRenderObject();
var local = box.globalToLocal(dragDown.globalPosition);
var rating = (local.dx / box.size.width * numStars * 2).ceilToDouble() / 2;
rating = max(0.0, rating);
rating = min(numStars.toDouble(), rating);
onChanged(rating);
},
onHorizontalDragUpdate: (dragUpdate) {
RenderBox box = context.findRenderObject();
var local = box.globalToLocal(dragUpdate.globalPosition);
var rating = (local.dx / box.size.width * numStars * 2).ceilToDouble() / 2;
rating = max(0.0, rating);
rating = min(numStars.toDouble(), rating);
onChanged(rating);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(
numStars, (index) => _buildStar(context, index),
growable: false)),
);
}
Widget _buildStar(BuildContext context, int index) {
Icon icon;
if (index >= rating) {
icon = Icon(
Icons.star_border,
color: Theme.of(context).primaryColor,
);
} else if (index > rating - 1 && index < rating) {
icon = Icon(
Icons.star_half,
color: Theme.of(context).primaryColor,
);
} else {
icon = Icon(
Icons.star,
color: Theme.of(context).primaryColor,
);
}
return icon;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment