DolDurma
DolDurma

Reputation: 17301

Flutter update current state of Riverpod saved data

Like with this sample code which that's into Riverpod sample codes for updating the current state of stored data:

state = [
  for (final todo in state)
    if (todo.id == id)
      Todo(
        id: todo.id,
        completed: todo.completed,
        description: description,
      )
    else
      todo,
];

i try to implementing that on my class data, but it saved data as new without updating selected state, my class data:

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);
}

here i try to found product's services and updating count of that as decrement count-1, but after search my code cause add new service into product and couldn't update

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)
  ]);

Upvotes: 0

Views: 654

Answers (1)

bizz84
bizz84

Reputation: 2272

Sounds like you need to implement a StateNotifier subclass. Here's just a sketch, I haven't tried it:

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)

]); } }

Make sure to read the documentation. This may also help:

https://codewithandrea.com/videos/flutter-state-management-riverpod/#statenotifierprovider

Upvotes: 1

Related Questions