做一排星星作为评级是微不足道的,但我不确定做随机数的正确 flutter 方法是什么?
换句话说,假设我的评分最多为 5 颗星,我该怎么做,只有一颗或两颗星?我可以有一个 switch 语句,并返回带有一两颗星的适当行小部件,但这似乎是一种丑陋的方法。
有没有合适的 Flutter/Dart 方法来做这种事情?
(我的问题当然不仅仅是这个,我想找到做这种事情的正确的 flutter 方法)
最佳答案
通过回答这个问题:How to create rating star bar properly?
同时,我给出了一个星级评级小部件的示例,它可以与任意数量的星级(默认为 5)一起使用。
typedef void RatingChangeCallback(double rating);
class StarRating extends StatelessWidget {
final int starCount;
final double rating;
final RatingChangeCallback onRatingChanged;
final Color color;
StarRating({this.starCount = 5, this.rating = .0, this.onRatingChanged, this.color});
Widget buildStar(BuildContext context, int index) {
Icon icon;
if (index >= rating) {
icon = new Icon(
Icons.star_border,
color: Theme.of(context).buttonColor,
);
}
else if (index > rating - 1 && index < rating) {
icon = new Icon(
Icons.star_half,
color: color ?? Theme.of(context).primaryColor,
);
} else {
icon = new Icon(
Icons.star,
color: color ?? Theme.of(context).primaryColor,
);
}
return new InkResponse(
onTap: onRatingChanged == null ? null : () => onRatingChanged(index + 1.0),
child: icon,
);
}
@override
Widget build(BuildContext context) {
return new Row(children: new List.generate(starCount, (index) => buildStar(context, index)));
}
}
然后你可以使用它
class Test extends StatefulWidget {
@override
_TestState createState() => new _TestState();
}
class _TestState extends State<Test> {
double rating = 3.5;
@override
Widget build(BuildContext context) {
return new StarRating(
rating: rating,
onRatingChanged: (rating) => setState(() => this.rating = rating),
starCount: 2
);
}
}
关于dynamic - 如何做随机数的星星? (评分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666829/