Reputation: 1955
I have a class on type Map(Object,Object) where I know the keys are all strings. How can I easily convert it to a Map(String,Object)?
Specifically the object is coming from a Firestore query
Firestore.instance.collection('schedule').document('nfl-2018').snapshots().data.data
Upvotes: 9
Views: 9934
Reputation: 71853
There are a number of ways to convert or wrap the map.
The two primary ones are the Map.cast
method and the Map.from
constructor.
Map<Object, Object> original = ...;
Map<String, Object> wrapped = original.cast<String, Object>();
Map<String, Object> newMap = Map<String, Object>.from(first);
The wrapped
map created by Map.cast
is a wrapper around the original map. If the original map changes, so does wrapped
. It is simple to use but comes with an extra type check on every access (because the wrapper checks the types at run-time, and it has to check every time because the original map may have changed).
The map created by Map.from
is a new map, which means all the data from the original map are copied and type checked when the map is created, but afterwards it's a separate map that is not connected to the original.
Upvotes: 21
Reputation: 2386
Map.from
(doc here) seems to work fine as a way to convert maps. As noted by lrn in comments below, this creates a new Map copy of the desired type. It doesn't cast the existing map.
final Map<Object, Object> first = <Object, Object>{'a': 'test!', 'b': 1};
final Map<String, Object> second = Map<String, Object>.from(first);
You can try it out in DartPad here!
Upvotes: 6