Rushwin Jamdas
Rushwin Jamdas

Reputation: 386

Expected a value of type 'int', but got one of type 'String' when trying to add a new key,value to a map

I have a map like this:

map = {
   'container_1':0,
   'container_2':0,
   'container_3':0,
}

That's being created from an iterable like this:

map=Map.fromIterable(containerList, key: (e)=>e, value: (e)=>0);

But when I try to add this key and value, I get an error:

map['user']='User Name';

The error I get is:

Expected a value of type 'int', but got one of type 'String'

How do I add a key value to a map that has a different value type than what's already in it?

Upvotes: 0

Views: 2945

Answers (2)

Mohamed Reda
Mohamed Reda

Reputation: 1607

I'd prefer to initialize the map to have The key as String and the value as dynamic Because the dynamic makes your variable type to be determined at the run type with any errors

final map = <String, dynamic>{
   'container_1': 0,
   'container_2': 0,
   'container_3': 0,
  };
  
  map['user'] = 'User Name';

Upvotes: 0

ChessMax
ChessMax

Reputation: 2265

The type of the map variable is Map<String, int>, so you couldn't add a String value to it. If you can change map type to Map<String, Object> then you will be able to add String value to it. Like this:

  final map = <String, Object>{
   'container_1': 0,
   'container_2': 0,
   'container_3': 0,
  };
  
  map['user'] = 'User Name';

Upvotes: 1

Related Questions