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
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With