Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would you find a certain map entry by a specific value?

Given the following map:

"user":
     {
         "userid":0,
     },
"appData":{
     "title":"Test",
     "pages":1,
     "posts":[
        {
          "postid":27979530,
          "text":Test,
        },
         {
          "postid":7732445,
          "text":Test123,
        },
        {
          "postid":9463254,
          "text":Test568,
        },  
      ]
}    

Given that map I want to try to find the entry for postid 7732445 so I can return the text value of Test123

What is the best way of doing something like that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Given that

final Map<String, dynamic> json = {
  "user": {
    "userid": 0,
  },
  "appData": {
    "title": "Test",
    "pages": 1,
    "posts": [
      {
        "postid": 27979530,
        "text": "Test",
      },
      {
        "postid": 7732445,
        "text": "Test123",
      },
    {
        "postid": 9463254,
        "text": "Test568",
      },
    ]
  }
};

you could do this search by doing

json["appData"]["posts"]
  .firstWhere(
    (item) => item["postid"] == 7732445,
    orElse: () => <String, Object>{},
  )["text"]

Because of the orElse, this will return null if not found.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading