Urgent: How to add maps to a list in dart when the map is nested?

112 views
Skip to first unread message

Ananth Kumar

unread,
Jun 24, 2021, 6:16:00 AM6/24/21
to Flutter Development (flutter-dev)
Dear all,

Please check this stackoverflow question and help me. Basically, I need to add value of a map in a list on every iteration which will give history of values changed in the map. I got a response from a friend and that seems no working when the maps are nested. Please find below the actual map and kindly help me with a work around.


void main() {
  int count = 0;
  
  List<Map<String, dynamic>> listOfMoves = [];
 
  
  Map<String, dynamic> dummyMap = {
  
  '0':  { 
        "position": "0",
        "piece": "rook",
        "color": "black",
        },
    
   '1': {
      "position": "1",
      "piece": "knight",
      "color": "black",
        },
     
   '2': {
      "position": "2",
      "piece": "bishop",
      "color": "black",
    },
   '3':  { 
        "position": "0",
        "piece": "rook",
        "color": "black",
        },
    '4':  { 
        "position": "0",
        "piece": "rook",
        "color": "black",
        },
    };
  
  for (var i = 0; i < 5; i++) {
    //these will happen on every iterations
    count++;
    dummyMap['$i']['position'] = '$count';
    listOfMoves.add(Map.from(dummyMap));
    print(listOfMoves.toString());
    }
}

For example:
Output:
flutter: [{1: 1, 2: 1, 3: 1}] 
flutter: [{1: 2, 2: 2, 3: 2}, {1: 2, 2: 2, 3: 2}] 
flutter: [{1: 3, 2: 3, 3: 3}, {1: 3, 2: 3, 3: 3}, {1: 3, 2: 3, 3: 3}] 
flutter: [{1: 4, 2: 4, 3: 4}, {1: 4, 2: 4, 3: 4}, {1: 4, 2: 4, 3: 4}, {1: 4, 2: 4, 3: 4}] 
flutter: [{1: 5, 2: 5, 3: 5}, {1: 5, 2: 5, 3: 5}, {1: 5, 2: 5, 3: 5}, {1: 5, 2: 5, 3: 5}, {1: 5, 2: 5, 3: 5}]

Expected Output: 
[{1: 1, 2: 1, 3: 1}] 
[{1: 1, 2: 1, 3: 1}, {1: 2, 2: 2, 3: 2}] 
[{1: 1, 2: 1, 3: 1}, {1: 2, 2: 2, 3: 2}, {1: 3, 2: 3, 3: 3}] 
[{1: 1, 2: 1, 3: 1}, {1: 2, 2: 2, 3: 2}, {1: 3, 2: 3, 3: 3}, {1: 4, 2: 4, 3: 4}] 
[{1: 1, 2: 1, 3: 1}, {1: 2, 2: 2, 3: 2}, {1: 3, 2: 3, 3: 3}, {1: 4, 2: 4, 3: 4}, {1: 5, 2: 5, 3: 5}]

Thanks,
Ananth

Suzuki Tomohiro

unread,
Jun 24, 2021, 7:30:21 AM6/24/21
to Ananth Kumar, Flutter Development (flutter-dev)
Update the stackoverflow question with the more real example.

--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/4962765d-a553-4b0c-85ca-b31cdeed7439n%40googlegroups.com.

Ananth Kumar

unread,
Jun 24, 2021, 8:10:07 AM6/24/21
to Suzuki Tomohiro, Flutter Development (flutter-dev)
Hi, thanks!

I have edited the questions. Kindly check and help me with this issue.


Thank you!
Ananth
Reply all
Reply to author
Forward
0 new messages