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

求助:基于Model数据在Widget列表中动态渲染星级评分并着色

实现Flutter星级评分展示组件

1. 编写可复用的星级评分Widget

创建一个专门的RatingStars组件,接收评分值并渲染对应数量的金色星星:

import 'package:flutter/material.dart';

class RatingStars extends StatelessWidget {
  final int rating;

  const RatingStars({super.key, required this.rating});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min, // 仅占用必要宽度
      children: List.generate(5, (index) {
        // 判断当前星星是否需要染成金色
        final isFilled = index < rating;
        return Icon(
          Icons.star,
          color: isFilled ? Colors.amber : Colors.grey.shade300,
          size: 18, // 可根据UI需求调整星星大小
        );
      }),
    );
  }
}

2. 在列表中集成评分组件

遍历你的trendingHome数据列表,将RatingStars嵌入到列表项的布局中:

ListView.builder(
  padding: const EdgeInsets.all(16),
  itemCount: trendingHome.length,
  itemBuilder: (context, index) {
    final trendingItem = trendingHome[index];
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 展示封面图
            Image.asset(
              trendingItem.image,
              width: 80,
              height: 120,
              fit: BoxFit.cover,
            ),
            const SizedBox(width: 12),
            // 右侧内容区域
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    trendingItem.title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(trendingItem.subtitle),
                  const SizedBox(height: 8),
                  // 插入星级评分组件
                  RatingStars(rating: trendingItem.rating),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  },
)

自定义扩展说明

  • 若需要替换星星图标,可将Icons.star改为其他图标(比如未选中用Icons.star_outline)
  • 金色和灰色的颜色值可根据设计需求自行调整,比如用Colors.yellow或自定义RGB值
  • 星星大小通过size参数修改,适配不同的UI布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:52:56