![](/img/trans.png)
[英]In flutter with riverpod, how to update state on a page already in the navigation stack
[英]Flutter update current state of Riverpod saved data
就像这个示例代码一样,它包含在Riverpod
示例代码中,用于更新存储数据的当前状态:
state = [
for (final todo in state)
if (todo.id == id)
Todo(
id: todo.id,
completed: todo.completed,
description: description,
)
else
todo,
];
我尝试在我的班级数据上实现它,但它将数据保存为新数据而不更新选定状态,我的班级数据:
class OrderStructure {
final String title;
final List<SelectedProducts> products;
const OrderStructure(this.title, this.products);
}
class SelectedProducts {
final int id;
final List<SelectedProductServices> services;
SelectedProducts(this.id, this.services);
}
class SelectedProductServices {
final int id;
final int count;
final int cost;
const SelectedProductServices(this.id, this.count, this.cost);
}
在这里,我尝试找到产品的服务并将其更新为递减count-1
,但在搜索我的代码后,将新服务添加到产品中并且无法更新
void decrement(int productId, int serviceId) {
final newState = OrderStructure(state.title, [
...state.products,
for (final product in state.products)
if (product.id == productId)
for (final service in product.services)
if (service.id == serviceId)
SelectedProducts(productId, [
...product.services.where((s) => s.id == serviceId),
SelectedProductServices(service.id, service.count - 1, service.cost)
])
else
SelectedProducts(productId,product.services)
]);
听起来您需要实现StateNotifier
子类。 这只是一个草图,我还没有尝试过:
class OrderStructureState extends StateNotifier<OrderStructure> {
// TODO: Add constructor with default value
void decrement(int productId, int serviceId) {
state = OrderStructure(state.title, [
...state.products,
for (final product in state.products)
if (product.id == productId)
for (final service in product.services)
if (service.id == serviceId)
SelectedProducts(productId, [
...product.services.where((s) => s.id == serviceId),
SelectedProductServices(service.id, service.count - 1, service.cost)
])
else
SelectedProducts(productId,product.services)
]); } }
请务必阅读文档。 这也可能有帮助:
https://codewithandrea.com/videos/flutter-state-management-riverpod/#statenotifierprovider
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.