You need to enable JavaScript to run this app. 如何使用Riverpod更新Flutter中多层嵌套类的状态数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Riverpod更新Flutter中多层嵌套类的状态数据?

解决方案

你原来的写法有几个核心错误:

  • 重复展开了state.products,会导致列表里出现重复的商品
  • 构造SelectedProducts时第一个参数传错了,应该传商品id而不是整个products列表
  • 直接对单个service对象使用展开运算符...,类型不匹配

注意:因为你定义的所有数据类字段都是final不可变,所以不能直接修改原有实例的属性,必须逐层创建新的实例替换对应节点,才能正确触发状态更新。

以下是修正后的完整代码:

void increment(int productId, int serviceId, int serviceCost) {
  final found = state.products.indexWhere((product) => product.id == productId);
  if (found < 0) {
    // 原有新增商品的逻辑保持不变
    final List<SelectedProductServices> _s = [];
    _s.add(SelectedProductServices(serviceId, 1, serviceCost));
    state = OrderStructure(
      state.title,
      [...state.products, SelectedProducts(productId, _s)],
    );
  } else {
    // 拿到匹配到的目标商品
    final targetProduct = state.products[found];
    // 查找对应服务的下标
    final serviceIndex = targetProduct.services.indexWhere((s) => s.id == serviceId);
    // 生成新的服务列表
    List<SelectedProductServices> newServices = List.from(targetProduct.services);
    if (serviceIndex >= 0) {
      // 服务存在,count+1
      final oldService = newServices[serviceIndex];
      newServices[serviceIndex] = SelectedProductServices(
        oldService.id,
        oldService.count + 1,
        oldService.cost,
      );
    } else {
      // 服务不存在,新增
      newServices.add(SelectedProductServices(serviceId, 1, serviceCost));
    }
    // 生成新的商品实例
    final newProduct = SelectedProducts(targetProduct.id, newServices);
    // 生成新的products列表,替换对应下标的商品
    List<SelectedProducts> newProducts = List.from(state.products);
    newProducts[found] = newProduct;
    // 更新state
    state = OrderStructure(state.title, newProducts);
  }
}

如果项目中集成了freezed这类不可变数据生成工具,还可以用自带的copyWith方法简化逐层拷贝的代码,写法会更简洁,以上是不需要额外依赖的原生实现。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:00:01