Search code examples
flutterdartdart-null-safety

How do I access the value of a given key in a nested Map in Dart?


I am new in Dart and I have been trying to access the value of "farm_size" key in the following piece of code but unsuccessful. I can access up to "farms" like this

print(myData1[0]["farms"]);

But not any further. Any help will be appreciated. Thanks.

void main() {
  var myData1 = [
  {
    "id": 1,
    "first_name": "Jordan",
    "sur_name": "Zamunda",
    "member_n0": "AA1",
    "gender": "male",
    "phone": "123456789",
    "email": "jordan@example.com",
    "farms": [
      {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
      {"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
    ]
  }
];

  print(myData1[0]["farms"]);

}

Solution

  • inside farms, there is a list of more maps, to access those maps, you need to specify the index of the map you, for example we want to get the first map, we type:

    print(myData1[0]["farms"][0]);
    //this will print => {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"}
    
    //to get the name of this farm, you use the key 'farm_name' now:
    print(myData1[0]["farms"][0]['farm_name']);
    //prints=> SOUTH_FARM
    

    If you're running it in dartpad, this will work:

    void main() {
      
      var myData1 = [
      {
        "id": 1,
        "first_name": "Jordan",
        "sur_name": "Zamunda",
        "member_n0": "AA1",
        "gender": "male",
        "phone": "123456789",
        "email": "jordan@example.com",
        "farms": [
          {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
          {"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
        ]
      }
    ];
      List<Map<String,dynamic>> _list = myData1[0]["farms"]as List<Map<String,dynamic>> ;
      
      print(_list[0]['farm_name']);
    
    
    }