flutterdartgoogle-cloud-functions

Calling a Firebase Cloud Function gives me List<Map<Object?, Object?>> but how can I cast it to something I can use?


I am calling a Firebase Cloud Function like this:

final result = await FirebaseFunctions.instance.httpsCallable('users').call();
if (result.data != null) {
  final data = result.data as List<Object?>;
  for (final obj in data) {
    print(obj.runtimeType); // Gives me _Map<Object?, Object?>
    if (obj != null && obj is Map<Object?, Object?>) { // Is true
      final user = obj as Map<String?, dynamic>; // Throws exception
    }
  }
}

If I inspect result.data with the debugger I can see that it is a List of Map where the key is always a String and the value is of differnet types, so Map<String?, dynamic> make sense to me, but the cast fails.

How can I read values out of my result?


Solution

  • Since you need to cast each item in the map, you can't use as. Instead you can use cast like this:

    Map<String, dynamic> convertedMap = (obj as Map).cast<String, dynamic>();