Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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)
like image 758
Ant D Avatar asked Sep 12 '19 17:09

Ant D


2 Answers

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]}}

like image 146
Richard Heap Avatar answered Oct 04 '22 06:10

Richard Heap


Try initializing using {}

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

it will create an empty map and works perfectly fine.

like image 24
SKJ Avatar answered Oct 04 '22 04:10

SKJ