【问题标题】:Flutter update current state of Riverpod saved dataFlutter 更新 Riverpod 保存数据的当前状态
【发布时间】:2021-10-21 20:31:26
【问题描述】:

就像这个示例代码一样,它包含在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)
  ]);

【问题讨论】:

    标签: flutter dart riverpod


    【解决方案1】:

    听起来你需要实现一个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

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2021-11-29
      • 2015-10-24
      • 2021-01-28
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多