9

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

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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!

3 Comments

Wow adding a link to pre-written code is convenient! I'm definitely gonna do that from now on.
There are many different ways to convert a map, including wrapping the original by doing first.cast<String, Object>(), but the from method here is the correct choice if you want to create a new map.
@lrn I didn't know about cast, that seems worthy of an answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.