Home > Mobile >  Assigning int to nested Map<String, dynamic> resolves in Error: type 'int' is not a
Assigning int to nested Map<String, dynamic> resolves in Error: type 'int' is not a

Time:08-21

I get the following error

type 'int' is not a subtype of type 'Null' of 'value'

with this code snipped

Map<String, dynamic> test = {
  "meta": {
        "age": null,
        "gender": null,
        "height": null,
        "weight": null,
      },
  "test": "test"
};

test["meta"]["age"] = 20;

Why does dart thinks that test["meta"]["age"] has the type Null when I have specified that test["meta"]is dynamic?

How can I assign test["meta"]["age"] an integer value without having to further type my Map?

CodePudding user response:

The type of the map is here determined by what content you are putting into it. Yes, for the map Test, we get the correct type of the map based on provided type hints. But the inner Map defined by:

{
  "age": null,
  "gender": null,
  "height": null,
  "weight": null,
}

Does not come with any type hints. So Dart will automatically determine the type of this Map based on the provided values at initialization.

You can force a specific type here by doing:

Map<String, dynamic> test = {
  "meta": <String, dynamic>{
        "age": null,
        "gender": null,
        "height": null,
        "weight": null,
      },
  "test": "test"
};
  •  Tags:  
  • dart
  • Related