Map<Object? Object> is not a subtype of type 'Map<String, dynamic> – Flutter

by
Ali Hasan
firebase firebase-realtime-database flutter flutter-dependencies

Quick Fix: Change your Map<Object?, Object?> to Map<dynamic, dynamic>.

The Solutions:

Solution 1: {title}

The provided solution is a simple and straightforward fix to the error message you’re encountering. As the error suggests, the issue lies in the type mismatch between the data you’re trying to retrieve from Firebase and the type expected by your code.

The code you provided expects data from Firebase to be in the form of a ‘Map‘, while the actual data is coming in as a ‘Map‘. To resolve this mismatch, you need to convert the data type to match the expected type.

This can be achieved using the following code snippet:

“`
Map snapshotData = snapshot.data!.snapshot.value as dynamic;
“`

By converting the data to ‘Map‘, you’re essentially telling Flutter that you’re expecting a map with dynamic keys and dynamic values, which is the type of data that’s being fetched from Firebase.

After making this change, the error message should disappear, and you’ll be able to successfully retrieve and display the data from your Firebase database.

Solution 2: Casting the Data

In order to resolve the type mismatch error, you can cast the data snapshot to the desired type before iterating over it. This is because the snapshot stores the data in a generic Map<Object?, Object?> format.

To cast the data, use the following code:

Map<Object?, Object?> dataSnapshot = snapshot.data!.snapshot;
Map<String?, dynamic> castedData = dataSnapshot.cast<String?, dynamic>();

Now, you can iterate over the casted data without encountering type mismatch errors:

castedData.values.forEach((key, value) {
  tips.add(value);
});

Q&A

How can I fix the error "type ‘_Map<Object?, Object?>’ is not a subtype of type ‘Map<String?, dynamic>’ in type cast" while reading data from firebase ?

You need to cast your data to the type you want. Map<Object?, Object> can be cast to the type you want by the following code

Flutter retrieving data from firebase gives error Map<Object? Object> is not a subtype of type ‘Map<String, dynamic>

All you need to do is :Map<dynamic,dynamic> snapshotData = snapshot.data!.snapshot.value as Map<dynamic,dynamic>;

Flutter retrieving data from firebase gives error Map<Object? Object> is not a subtype of type ‘Map<String, dynamic>

My workaround was this cast: myJson = Map<String, dynamic>.from (snapshot.value as Map);

Video Explanation:

The following video, titled "I built a movement map but all the jumps are off of doors Part 1 ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Timestamp strafe 0:00 Intro 1:13 Checkpoints 1-7 1:57 Checkpoints 8-12 2:39 Checkpoints 13-21 3:20 Checkpoints 22-24 4:09 Checkpoints 25-28 ...