Home > database >  Cannot filter map using removeWhere because 'Cannot modify unmodifiable map' despite a non
Cannot filter map using removeWhere because 'Cannot modify unmodifiable map' despite a non

Time:07-21

I am writing a function to read from a google sheet. It throws an error despite me not assigning anything as final or constant, what am I missing? (Sorry if it's obvious, I am still learning).

static Future<List<Client>?> getRouteById({required String id}) async {

    // Get all routeIDs from client sheet
    List<String>? routeIds = await clientSheet!.values.columnByKey('route');

    // Converts list to map with indices as keys
    Map<int, String> idMap = routeIds!.asMap();

    // Strips away all non relevant routeID's
    idMap.removeWhere((key, value) => value != id); // <- ERROR

    // Gets client data from each index
    List<Client> route = [];
    idMap.forEach((key, value) async {
      List<dynamic> clientList = await clientSheet!.values.row(key);
      route.add(Client(clientList));
    });
    return route;
  }

It doesn't highlight that it is an error until I compile and run to a Google Pixel 5 emulator. This is the full error message:

E/flutter (10996): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Unsupported operation: Cannot modify unmodifiable map

E/flutter (10996): #0 _UnmodifiableMapMixin.removeWhere (dart:collection/maps.dart:294:5)

E/flutter (10996): #1 SheetsAPI.getRouteById (package:bugman_route_v2/helper/sheetsAPI.dart:63:12)

E/flutter (10996): asynchronous suspension

CodePudding user response:

asMap will return immutable value back https://api.flutter.dev/flutter/dart-core/List/asMap.html

so you have to create another one first I would do

// Converts list to map with indices as keys
Map<int, String> idMap = routeIds!.asMap();
Map<int, String> idMapCopy = Map.from(idMap); <- new code

// Strips away all non relevant routeID's
idMapCopy.removeWhere((key, value) => value != id);

CodePudding user response:

you need to initialize it not as map..

here fix :

Map<int, String> idMap = Map.from(routeIds.asMap());
  • Related