Riverpod / Flutter 中的现有状态编辑

Existing state editing in Riverpod / Flutter

如何操作 Riverpod 中的现有状态。我是 FlutterRiverpod 的初学者。当我尝试将 1 添加到 Order 时,弹出错误提示:

Error: A value of type 'int' can't be assigned to a variable of type 'List'.

final OrderPaperProvider = StateNotifierProvider<OrderPaper, List<Order>>((ref) {
  return OrderPaper();
});

@immutable
class Order {
  final String product_id;
  final String product_name;
  final int product_price;
  final int product_count;

  Order({required this.product_id, required this.product_name, required this.product_price, required this.product_count});

  Order copyWith({product_id, product_name, product_price, product_count}) {
    return Order(
      product_id: product_id,
      product_name: product_name,
      product_price: product_price,
      product_count: product_count,
    );
  }
}

class OrderPaper extends StateNotifier<List<Order>> {
  OrderPaper() : super([]);

  void addOrder(Order order) {
    for (var x = 0; x < state.length; x++) {
      if (state[x].product_id == order.product_id) {
        addOneToExistingOrder(x, order);
        return;
      }
    }
    state = [...state, order];
  }

  void removeOrder(String product_id) {
    state = [
      for (final order in state)
        if (order.product_id != order) order,
    ];
  }

  void addOneToExistingOrder(index, Order order) {
    state = state[index].product_count + 1; // <--------- Error in this line
  }

  void clearOrderPaper() {
    state = [];
  }
}

您发布的代码中发生的事情基本上是这样的:

  • 你告诉它用整数更新 List<Order> 的状态。

  • 这是因为state[index].product_count + 1实际上等于一个数,例如1+2=3。

  • 所以你告诉它,state = 3,这会导致你的错误。

你需要做的是用项目列表和编辑的项目创建一个新状态,就像这样(你不需要传递索引,你可以在函数中获取它):

 void addOrder(Order order) {
//find if the product is in the list. The index will not be -1.
 final index = state.indexWhere((entry) => entry.product_count == order. product_count);

    if (index != -1) {
      //if the item is in the list, we just edit the count
      state = [
        ...state.sublist(0, index),
        order.copyWith(product_count: state[index].product_count + 1),
        ...state.sublist(index + 1),
      ];  
    }else {
       //otherwise, just add it as a new entry.
      state = [...state, order],
     }
    
}