I am having a HashMap of <String, dynamic> and i would like to populate the map. The problem i am having is that its telling me the map is not of type dynamic. Below is my code
HashMap<String, dynamic> stuff1 = {"id": 1, "region": "North",
"shippingAddress": "Flyover", "list": []};
How can i create a HashMap of <String, dynamic>, i know some would suggest using HashMap<String, Object> stuff but i am having a list like below
List<HashMap<String, dynamic>>? stuffList;
which has data being populate from a server, but i just want to add stuff1 to the top of the list and i would like to add it with a HashMap of <String, dynamic> because if i add with <String, Object> it won't work
CodePudding user response:
Try to explicitly instantiate HashMap
final Map<String, dynamic> stuff1 = HashMap()..addAll({"id": 1, "region": "North", "shippingAddress": "Flyover", "list": []});
The other solution might be possible is to as HashMap<String, dynamic> as the end of stuff1
Map<String, dynamic> stuff1 = {"id": 1, "region": "North", "shippingAddress": "Flyover", "list": []} as HashMap<String, dynamic>;
CodePudding user response:
Dart Map literals (e.g. {"id": 1, "region": "North", ...} create objects that conform to the abstract Map interface. By default, the constructed objects are LinkedHashMap instances, but the static (known at compile-time) type of the literal is just Map.
Map is the abstract base type for a number of implementations (such as LinkedHashMap and HashMap). In general, you cannot directly assign a base type where a derived (more specific) type is expected; that might not be safe. You also can't just cast the object (which is LinkedHashMap) to a HashMap; neither LinkedHashMap nor HashMap derives from the other.
If you really want an unordered HashMap, you must use a HashMap constructor. For example:
HashMap<String, dynamic> stuff1 = HashMap.of({
"id": 1,
"region": "North",
"shippingAddress": "Flyover",
"list": [],
});
Alternatively consider using a regular Map (which, again, by default is a LinkedHashMap), which already is hash-based but which additionally maintains insertion order.
