Search code examples
flutterdartriverpodflutter-riverpod

Flutter riverpod Unsupported operation: Cannot add to an unmodifiable list


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

Solution

  • 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]