0

How to access a Map element value by key, when a Map is inside a list?

'rooms': [
        {
          'roomNumber': 1,
          'roomBeds': 1,
          'roomColor': 1,
          'roomNumOfDwellers': 0,
          'roomDwellers': [
          ]
        },
        {
          'roomNumber': 2,
          'roomBeds': 3,
          'roomColor': 2,
          'roomNumOfDwellers': 0,
          'roomDwellers': [
          ]
        },
      ]

Tried this, doesn't work:

myPODO.rooms[1].['roomBeds']

The error message is:

Class '_InternalLinkedHashMap' has no instance getter 'roomBeds'. Receiver: _LinkedHashMap len:5 Tried calling: roomBeds

2 Answers2

2

Store the items in a list of Map and you can then print the values by key names.

void main() {

  List<Map<String, dynamic>> rooms = [
        {
          'roomNumber': 1,
          'roomBeds': 1,
          'roomColor': 1,
          'roomNumOfDwellers': 0,
          'roomDwellers': [
          ]
        },
        {
          'roomNumber': 2,
          'roomBeds': 3,
          'roomColor': 2,
          'roomNumOfDwellers': 0,
          'roomDwellers': [
          ]
        },
      ];

  print(rooms[1]['roomBeds']);
}

gegobyte
  • 4,045
  • 6
  • 34
  • 64
  • It worked, thank you very much! The problem was in the dot between rooms[1] and ['roomBeds'], it wasn't needed. – Aleksander Barsukov Apr 29 '20 at 11:28
  • @AleksanderBarsukov If this answer solved your problem, you can mark it as accepted answer by clicking the check mark beside the answer. – gegobyte Apr 29 '20 at 12:15
  • I tried to do that before writing back, but apparently, I don't have enough reputation to do that yet. I promise to get back and upvote your answer after I gain the needed reputation :) – Aleksander Barsukov Apr 29 '20 at 12:23
2

try to replace

myPODO.rooms[1].['roomBeds']

with

myPODO.rooms[1]['roomBeds']
GJJ2019
  • 4,036
  • 3
  • 11
  • 19