Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unsupported operation: Cannot add to an unmodifiable list unsing Bloc

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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

>Solution :

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)));
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading