如何在地图中初始化列表?
Map<String,Map<int,List<String>>> myMapList = Map();
我得到一个错误:
The method '[]' was called on null.
I/flutter (16433): Receiver: null
I/flutter (16433): Tried calling: [](9)
答案 0 :(得分:2)
只需在创建地图时添加元素,或稍后add
将其添加。例如:
var myMapList = <String, Map<int, List<String>>>{
'someKey': <int, List<String>>{
0: <String>['foo', 'bar'],
},
};
或
var m2 = <String, Map<int, List<String>>>{}; // empty map
m2['otherKey'] = <int, List<String>>{}; // add an empty map at the top level
m2['otherKey'][2] = <String>[]; // and an empty list to that map
m2['otherKey'][2].add('baz'); // and a value to that list
print(m2);
打印{otherKey: {2: [baz]}}
答案 1 :(得分:0)
尝试使用{}
Map<String,Map<int,List<String>>> myMapList = {}; // just add {}
它将创建一个空地图,并且可以正常工作。