Home > Blockchain >  Flutter riverpod Unsupported operation: Cannot add to an unmodifiable list
Flutter riverpod Unsupported operation: Cannot add to an unmodifiable list

Time:09-12

After creating a simple order notifier i want to add new data to one list of my customer orders with .add() in create method of that but i get this error:

Unsupported operation: Cannot add to an unmodifiable list

order notifier:

final orderStructureProvider = StateNotifierProvider<OrderNotifier, OrderStructure>((ref) => OrderNotifier());

class OrderNotifier extends StateNotifier<OrderStructure> {
  OrderNotifier() : super(_initial);

  static const OrderStructure _initial = OrderStructure(
    address: Address(
      //...
    ),
    breads: [],
    baker: [],
    paymentType: 1,
  );

  void create(BreadStructure _bread) {
    final newState = OrderStructure(
      address: state.address,
      breads: [...state.breads],
      baker: [...state.state.baker],
      paymentType: state.paymentType,
    );

    /* I GET ERROR IN THIS LINE OF CODE */
    newState.breads.add(_bread);
    state = newState;
  }

  //...
}

//...

@freezed
abstract class OrderStructure with _$OrderStructure {
  const factory OrderStructure({
    required Address address,
    required List<BreadStructure> breads,
    required List<Map<String, dynamic>> baker,
    required int paymentType,
  }) = _OrderStructure;

  factory OrderStructure.fromJson(Map<String, dynamic> json) => _$OrderStructureFromJson(json);
}

@freezed
abstract class BreadStructure with _$BreadStructure {
  const factory BreadStructure({
    required int id,
    required String name,
    required int count,
  }) = _BreadStructure;

  factory BreadStructure.fromJson(Map<String, dynamic> json) => _$BreadStructureFromJson(json);
}

now into BreadItem class which that extends from HookConsumerWidget i try to create and add new data with this method:

final order = ref.read(orderStructureProvider.notifier);

order.create(BreadStructure(id: id, name: name, count: 1));

CodePudding user response:

You might try this code for adding a new bread to breads list. Because your newState.breads is immutable, instead of mutating you might try to instantiate it to a new value.

newState.breads = [...newState.breads, _bread]

CodePudding user response:

void create(BreadStructure _bread) {
    final newState = OrderStructure(
      address: state.address,
      breads: [...state.breads],
      baker: [...state.state.baker],
      paymentType: state.paymentType,
    );

    /* I GET ERROR IN THIS LINE OF CODE */
    newState.breads.add(_bread);
    state = newState;
  }

You can't make newState final here. If a variable is final, you can't change its value in future. Just remove the final keyword from newState and it will work.

Write this instead:

OrderStructure newState = OrderStructure(
    address: state.address,
    breads: [...state.breads],
    baker: [...state.state.baker],
    paymentType: state.paymentType,
);
  • Related