You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart/Flutter中实现可定制的星级评分Widget?

实现可定制的Flutter星级评分Widget

我正尝试制作一个可定制的星级评分Widget,使其每次使用时能呈现不同样式的星级。现有基础实现代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';

class Stars extends StatelessWidget {
  const Stars({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: 
      [
      Icon(Icons.star, color: Colors.yellow, size: 20,),
      Icon(Icons.star, color: Colors.yellow, size: 20,),
      Icon(Icons.star, color: Colors.yellow, size: 20,),
      Icon(Icons.star_outlined, color: Color.fromARGB(255, 0xE1, 0xE1, 0xEA), size: 20,),
      Icon(Icons.star_outlined, color: Color.fromARGB(255, 0xE1, 0xE1, 0xEA), size: 20,),
      ]
    );
  }
}

当前输出UI为3个黄色填充星+2个灰色轮廓星的样式。

当然可以实现,只需要给Stars组件添加可配置的参数,让它能根据传入的值动态生成不同样式的星级评分。以下是优化后的实现:

可定制星级评分组件代码

import 'package:flutter/material.dart';

class Stars extends StatelessWidget {
  // 当前评分(需小于等于总星数)
  final double rating;
  // 总星数
  final int totalStars;
  // 填充星的颜色
  final Color filledColor;
  // 空星的颜色
  final Color emptyColor;
  // 星星大小
  final double starSize;
  // 填充星使用的图标
  final IconData filledIcon;
  // 空星使用的图标
  final IconData emptyIcon;

  const Stars({
    Key? key,
    required this.rating,
    this.totalStars = 5,
    this.filledColor = Colors.yellow,
    this.emptyColor = const Color.fromARGB(255, 0xE1, 0xE1, 0xEA),
    this.starSize = 20.0,
    this.filledIcon = Icons.star,
    this.emptyIcon = Icons.star_outlined,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: List.generate(totalStars, (index) {
        // 判断当前位置的星星是否需要填充,支持半星逻辑
        final isFilled = index < rating.floor() || 
            (index == rating.floor() && rating - index >= 0.5);
        
        return Icon(
          isFilled ? filledIcon : emptyIcon,
          color: isFilled ? filledColor : emptyColor,
          size: starSize,
        );
      }),
    );
  }
}

关键定制点说明

  • 评分与总星数:通过rating和totalStars控制显示的填充星数量,支持半星(例如rating=3.5时显示3个全星+1个半星,可按需调整半星判断逻辑)
  • 颜色定制:filledColor和emptyColor分别设置填充星和空星的颜色
  • 大小定制:starSize控制星星的整体尺寸
  • 图标样式:filledIcon和emptyIcon可以替换成不同的星星图标(比如Icons.star_rounded、Icons.star_border等)

示例用法

// 基础样式(3.5星,默认5总星)
Stars(rating: 3.5)

// 红色填充星,更大尺寸
Stars(
  rating: 4,
  filledColor: Colors.red,
  starSize: 28,
)

// 自定义图标,6总星
Stars(
  rating: 5,
  totalStars: 6,
  filledIcon: Icons.star_rounded,
  emptyIcon: Icons.star_outline_rounded,
)

这样每次使用Stars组件时,只需传入不同的参数就能生成不同样式的星级评分了。

内容的提问来源于stack exchange,提问作者shotmeinthehead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:55:22