You need to enable JavaScript to run this app. Flutter使用Riverpod管理订单状态 新增/更新服务功能实现问题
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用Riverpod管理订单状态 新增/更新服务功能实现问题

修正后的increment方法实现

以下是符合需求的可直接运行的正确实现:

void increment({required int productId, required int serviceId, required int serviceCost}) {
  // 复制原有商品列表,避免直接修改原状态
  List<SelectedProducts> updatedProducts = List.from(state.products);
  // 查找对应productId的商品下标
  final productIndex = updatedProducts.indexWhere((product) => product.id == productId);

  if (productIndex != -1) {
    // 商品已存在,复制当前商品的服务列表
    final currentProduct = updatedProducts[productIndex];
    List<SelectedProductServices> updatedServices = List.from(currentProduct.services);
    // 查找对应serviceId的服务下标
    final serviceIndex = updatedServices.indexWhere((service) => service.id == serviceId);

    if (serviceIndex != -1) {
      // 服务已存在,count加1
      final currentService = updatedServices[serviceIndex];
      updatedServices[serviceIndex] = SelectedProductServices(
        currentService.id,
        currentService.count + 1,
        currentService.cost,
      );
    } else {
      // 服务不存在,新增服务默认count为1
      updatedServices.add(SelectedProductServices(serviceId, 1, serviceCost));
    }

    // 替换更新后的商品
    updatedProducts[productIndex] = SelectedProducts(currentProduct.id, updatedServices);
  } else {
    // 商品不存在,新增商品和对应服务
    updatedProducts.add(SelectedProducts(
      productId,
      [SelectedProductServices(serviceId, 1, serviceCost)],
    ));
  }

  // 替换状态触发更新
  state = OrderStructure(state.title, updatedProducts);
}

原代码核心问题说明

  • 构造新状态时先展开了全量原有商品,后续遍历又重复添加了匹配的商品,导致商品重复
  • 错误使用contains方法判断id是否存在,列表存储的是对象不是int类型的id,判断逻辑完全失效
  • 新增商品时错误把serviceId作为productId传入,导致商品id异常
  • 直接修改状态内部的列表属性,不符合Riverpod不可变状态的更新规范,容易出现UI不刷新的问题

额外优化建议

测试代码中直接取_orderProvider.state.products[0]会在初始无商品时报错,建议修改为判空处理:

Text('product`s service count: ${_orderProvider.state.products.isNotEmpty ? _orderProvider.state.products[0].services.length : 0}')

如果要进一步保证状态的不可变性和更新可靠性,建议使用freezed生成数据类,自动重写==和hashCode,避免不必要的状态异常。

内容的提问来源于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 22:39:02