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

如何在Flutter的ListView.builder中为每个索引项设置独立专属变量

实现方案

1. 定义专属数据模型

首先创建Ticket类统一存储每个索引项需要的三个字段,保证类型安全,避免异构List的类型转换问题:

class Ticket {
  // 对应字符串类型的阶段名
  final String phase;
  // 对应double类型的价格
  final double price;
  // 对应整数类型的数量,支持修改
  int qty;

  Ticket({
    required this.phase,
    required this.price,
    required this.qty,
  });
}

2. 初始化独立的Ticket列表

在当前页面的State类中定义Ticket列表,不要放在全局作用域,列表长度和你的data['phases']长度完全一致,每个索引对应独立的Ticket实例:

class _YourPageState extends State<YourPage> {
  List<Ticket> tickets = [];

  @override
  void initState() {
    super.initState();
    // 页面初始化时生成对应长度的Ticket列表
    tickets = List.generate(
      data['phases'].length,
      (index) => Ticket(
        phase: data['phases'][index]['phase'],
        price: double.parse(data['phases'][index]['price'].toString()),
        // 初始数量可根据需求调整,这里默认设为0
        qty: 0,
      ),
    );
  }

3. 修改ListView.builder逻辑

修正原有加减按钮的逻辑,点击时仅修改当前索引对应的Ticket实例值,同步刷新UI(已修复原代码中Expanded嵌套错误的问题):

ListView.builder(
  itemCount: data['phases'].length,
  itemBuilder: (BuildContext context, int i) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: InkWell(
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: MediaQuery.of(context).size.width * 0.28,
                child: Text(
                  tickets[i].phase,
                  style: const TextStyle(
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1),
                ),
              ),
              Text(
                tickets[i].price.toString(),
                style: const TextStyle(
                    color: Colors.green,
                    letterSpacing: 1,
                    fontWeight: FontWeight.w400),
              ),
              Row(
                children: [
                  InkWell(
                    onTap: () {
                      // 仅修改当前索引的数量,可自行增加数量上限判断
                      if(tickets[i].qty > 0) {
                        setState(() {
                          tickets[i].qty--;
                        });
                      }
                    },
                    child: const Icon(
                      CupertinoIcons.minus,
                      color: Colors.red,
                      size: 16,
                    ),
                  ),
                  const SizedBox(width: 10),
                  // 展示当前索引对应的独立数量值
                  Text(tickets[i].qty.toString()),
                  const SizedBox(width: 10),
                  InkWell(
                    onTap: () {
                      setState(() {
                        tickets[i].qty++;
                      });
                    },
                    child: const Icon(
                      CupertinoIcons.plus,
                      color: Colors.green,
                      size: 16,
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  },
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:05