skip to Main Content

i am using bloc to add and remove from am list..

my bloc state is like this,

@freezed
class InterestActionState with _$InterestActionState {
  factory InterestActionState({
    required bool isSubmitting,
    required List<String> selectedInterest,
    required Option<Either<InterestFailure, Unit>>
        intrestFailureOrSuccessOption,
  }) = Initial;

  factory InterestActionState.initial() => InterestActionState(
        isSubmitting: false,
        selectedInterest: <String>[],
        intrestFailureOrSuccessOption: none(),
      );

  const InterestActionState._();
}

also i am adding to the list like this

  void addInterestToMyList(
    AddMyList event,
    Emitter<InterestActionState> emit,
  ) {
    emit(state.copyWith(
        selectedInterest: state.selectedInterest..add(event.selectedInterest)));
  

}

and to Remove from the List is

 void removeInterestToMyList(
    RemoveFromList event,
    Emitter<InterestActionState> emit,
  ) {
    emit(state.copyWith(
        selectedInterest: state.selectedInterest
          ..remove(event.selectedInterest)));
  }

but i keep getting flutter: Unsupported operation: Cannot add to an unmodifiable list

2

Answers


  1. change your code into:

      void addInterestToMyList(
        AddMyList event,
        Emitter<InterestActionState> emit,
      ) {
        emit(state.copyWith(
            selectedInterest: [...state.selectedInterest, event.selectedInterest]));
    

    and to remove it, create a new lazy list without editing the original one:

    emit(state.copyWith(
        selectedInterest: state.selectedInterest.where((e) => e != event.selectedInterest).toList()));
    

    this should solve your issue

    Login or Signup to reply.
  2. state.selectedInterest must be unmodifiable, and remove and add modify the list in place (it modifies the list and doesn’t create a copy).

    You can create a copy yourself using .toList():

    Add:

     void addInterestToMyList(
        AddMyList event,
        Emitter<InterestActionState> emit,
      ) {
        emit(state.copyWith(
            selectedInterest: state.selectedInterest.toList()..add(event.selectedInterest)));
      
    

    Remove:

    void removeInterestToMyList(
        RemoveFromList event,
        Emitter<InterestActionState> emit,
      ) {
        emit(state.copyWith(
            selectedInterest: state.selectedInterest.toList()
              ..remove(event.selectedInterest)));
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search