Skip to content

Possible bug? foo["a"]="b" results in TypeError, even if foo is a Map<String,dynamic> #892

Closed
@sloisel

Description

@sloisel

I think I understand why this "bug" happens but it was so baffling, my head did a couple of turns like in the exorcist when it happened. Consider this code:

Map fixprobset(Map<String,dynamic> P) {
  if(!P.containsKey("name")) {
    P["name"] = (P["tileset"] as List<String>).join(" ");
  }
  if(P.containsKey("children")) {
    final Q = P["children"];
    for(var k=0; k<Q.length;k++) Q[k] = fixprobset(Q[k]);
  }
  return P;
}

One would expect the parameter P to be of type Map<String,dynamic>, since that's what it says right there, but sometimes P.runtimeType is, e.g. Map<String,List<String>> and then the line P["name"]=... results in a baffling run-time TypeError. By abusing Map<String,dynamic>.from() and friends, I was able to get around this but it seems like a crazy way to do things. It was even more bizarre in my case because, by adding one field to my data structure, whichever map was getting runtimeTyped to Map<String,List>, was instead correctly typed as Map<String,dynamic>, which was getting around the real problem here, which is that the compiler ignores my type declaration in the parameter list of the function.

Here's a gist:

https://dartpad.dev/d041fe1d97bf1f6a378a45bc81cb4f28

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThere is a mistake in the language specification or in an active document

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions