Riverpod / Flutter中的现有状态编辑



如何操纵Riverpod中的现有状态。我是FlutterRiverpod的初学者。当我尝试添加一个到Order错误弹出并说:

错误:int类型的值不能赋值给int类型的变量"列表"。

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],
}

}

最新更新