flutter: Can't modify list because of Unsupported operation: Cannot modify an unmodifiable list
Asked Answered
R

0

7

I'm trying to modify item value in list, which always results Can't modify list because of Unsupported operation: Cannot modify an unmodifiable list

I'm using bloc state-management and freezes as code generator. Here is my code:

Get roles from server and add List to role

Future<RoleWithNeeds> getRoleWithNeeds({
    required RoleWithNeeds selectedRoles,
  }) async {
    final dataFromApi = await _apiClient.fetchNeedsByRoles(selectedRoles.idRole);

    final needsApi = dataFromApi.data;
    final needsRepository = <Need>[];

    // convert to a repository model
    for (var i = 0; i < needsApi.length; i++) {
      needsRepository.add(Need(
        id: needsApi[i].id,
        name: needsApi[i].name,
        createdAt: needsApi[i].createdAt,
      ));
    }

    return selectedRoles.copyWith(needs: needsRepository);
  }

Part when I try to modify nested array in RoleWithNeeds

FutureOr<void> _onClickNeed(_ClickNeed event, Emitter<NeedState> emit) {
    emit(_Load());

    try {
      for (var role in _listRoleWithNeeds) {
        for (var need in role.needs) {
          if (need == event.need) {
            final changedNeed =
                event.need.copyWith(isSelected: !event.need.isSelected);
            _listRoleWithNeeds[_listRoleWithNeeds
                    .indexWhere((element) => element.needs.contains(need))]
                .needs[_listRoleWithNeeds[_listRoleWithNeeds
                    .indexWhere((element) => element.needs.contains(need))]
                .needs
                .indexOf(event.need)] = changedNeed;

            if (_searchedList.contains(event.need)) {
              _searchedList[_searchedList.indexOf(event.need)] = changedNeed;
            }

            break;
          }
        }
      }

      _selectedList.clear();
      for (final roleWithNeeds in _listRoleWithNeeds) {
        for (final need in roleWithNeeds.needs) {
          if (need.isSelected){
            _selectedList.add(need);
          }
        }
      }

      if(_isSelectedButtonPressed){
        emit(_Search(needs: _selectedList, sum: _selectedList.length));
      }
      else{
        !_isSearched
            ? emit(_Success(model: _listRoleWithNeeds, sum: _selectedList.length))
            : emit(_Search(needs: _searchedList, sum: _selectedList.length));
      }

    } catch (e) {
      emit(_Error(e.toString()));
    }
  }

RoleWithNeeds and Need models

@freezed
class RoleWithNeeds with _$RoleWithNeeds {
  factory RoleWithNeeds({
    required int idRole,
    required String nameRole,
    required String svgUrl,
    @Default(true) bool isShort,
    @Default(<Need>[]) List<Need> needs,
    @Default(false) bool isSelected,
  }) = _RoleWithNeeds;

  factory RoleWithNeeds.fromJson(Map<String, dynamic> json) =>
      _$RoleWithNeedsFromJson(json);


}

@freezed
class Need with _$Need {
  factory Need({
    required int id,
    required String name,
    @Default(false) bool isSelected,
    String? createdAt,
  }) = _Need;

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

Please, help me. I can't understand my failure.

Requiem answered 23/6, 2022 at 12:59 Comment(2)
Whatever created the List object that you're trying to modify created it as an unmodifiable List. If you need to a List that you can modify, you'll need to make a copy of it first. You can create a shallow copy with var listCopy = [...originalList]; or var listCopy = originalList.toList();.Herwick
Thank you @jamesdin my code started working when i used .toList()Moulden

© 2022 - 2025 — McMap. All rights reserved.