dart语言:Map <Object,String>如何添加新对?

use*_*154 9 map dart

鉴于:

Map<WebSocket,String> mListUser;
mListUser= new  Map<WebSocket,String>();
Run Code Online (Sandbox Code Playgroud)

从我现在理解的添加新元素我应该做:

mListUser[socket]="string";
Run Code Online (Sandbox Code Playgroud)

而是我得到:

type 'String' is not a subtype of type 'int' of 'index'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

小智 7

也许有帮助

final test = Map<String, int>();
test.putIfAbsent('58', () => 56);
Run Code Online (Sandbox Code Playgroud)

如果键不存在,它将被放入地图中。

  • 我正在使用“Map&lt;DateTime, Lis&lt;Event&gt;&gt;”(事件是一个随机类)。每次我添加新对时,都会正确添加键(DateTime),但所有键中的列表都会被替换。有什么帮助吗?有任何想法吗? (2认同)

Ger*_*ero 6

也许有帮助。

Map<Object,String> map1= new Map<Object,String>();
Collections c = new Collections(); //some random class

map1[new Collections()]="arg1";
map1[c]="arg2";

map1.forEach((k,v)=>print("out: $k $v"));
print(map1[c]);
Run Code Online (Sandbox Code Playgroud)

得到这个输出:

out: Instance of 'Collections' arg2
out: Instance of 'Collections' arg1
arg2
Run Code Online (Sandbox Code Playgroud)