【问题标题】:How to do random number of stars? (rating)如何做随机数星星? (评分)
【发布时间】:2018-03-21 20:47:16
【问题描述】:

将一排星星作为评级是微不足道的,但我不确定随机数它们的正确颤振方式是什么?

换句话说,假设我的评分最高为 5 星,我该怎么做,只有一星或两星?我可以有一个 switch 语句,并返回带有一两个星的适当行小部件,但这些似乎是一种丑陋的方法。

有没有合适的 Flutter/Dart 方法来做这种事情?

(我的问题当然不仅仅是这个,我想找到做这种事情的正确颤振方法)

【问题讨论】:

标签: dynamic widget row flutter


【解决方案1】:

通过回答这个问题:How to create rating star bar properly?

同时,我给出了一个 Star rating 小部件的示例,它可以使用任意数量的星(默认为 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
      );
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2023-03-17
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多