簡體   English   中英

Flutter 更新 Riverpod 保存數據的當前狀態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM