简体   繁体   English

Dart/Flutter 如何初始化地图内的列表?

[英]Dart/Flutter How to initialize a List inside a Map?

How can I initialize a list inside a map?如何初始化地图内的列表?

Map<String,Map<int,List<String>>> myMapList = Map();

I get an error :我收到一个错误:

The method '[]' was called on null.
I/flutter (16433): Receiver: null
I/flutter (16433): Tried calling: [](9)

By just adding the elements when you create the map, or later by add ing them.通过在创建地图时添加元素,或者稍后通过add它们。 For example:例如:

var myMapList = <String, Map<int, List<String>>>{
  'someKey': <int, List<String>>{
    0: <String>['foo', 'bar'],
  },
};

or或者

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);

prints {otherKey: {2: [baz]}}打印{otherKey: {2: [baz]}}

Try initializing using {}尝试使用{}初始化

Map<String,Map<int,List<String>>> myMapList = {}; // just add {}

it will create an empty map and works perfectly fine.它将创建一个空地图并且工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM