Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart convert Map<Object,Object> to Map<String,Object>

Tags:

dart

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
like image 484
dakamojo Avatar asked Jul 09 '18 20:07

dakamojo


People also ask

How do you convert a dart string to a map?

Convert a Map to a Query String We can use the queryParameters parameter of the Uri class to make a query string from a map. Note that the Uri class goes with dart:core so that you can use it without importing anything.

How do you turn an object into a dart map?

Using Iterable forEach() method We can convert Dart List of Objects to Map in another way: forEach() method. var map = {}; list. forEach((customer) => map[customer.name] = {'email': customer.

How do you change an object to a map in flutter?

You can try this: var data = { "key1": "value1", "key2": "value2", "key3": "value3", }; var myMap = Map<String, dynamic>. from(data); print(myMap); With dynamic in Map<String, dynamic> we can have the values of the map of any type.


2 Answers

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.

like image 155
lrn Avatar answered Sep 22 '22 13:09

lrn


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!

like image 43
emerssso Avatar answered Sep 24 '22 13:09

emerssso