Dart/Flutter How to initialize a List inside a Map?

By just adding the elements when you create the map, or later by adding them. 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]}}


Try initializing using {}

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

it will create an empty map and works perfectly fine.

Tags:

Dart

Flutter