简体   繁体   中英

Dart/Flutter How to access element of Map inside a list

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

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']);
}

try to replace

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

with

myPODO.rooms[1]['roomBeds']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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