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

Time:11-12

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?

CodePudding user response:

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.

  • Related