Home > front end >  get a map value by key from a list of maps in dart flutter
get a map value by key from a list of maps in dart flutter

Time:05-22

I need to get the value of a data when the name matches the key in a list of maps. Something like this:

List<Map> dataList = [];
await friends.doc(" 2348******").collection("Friends").get().then((value) {
  for (var element in value.docs) {
    dataList.add(element.data());
  }
  print("${dataList.where((element) => element == " 23789900")}");
});

I expect this to print out: John doe I found something similar but they didnt solve my problem

CodePudding user response:

Try this example:

List<Map> dataList = [];
await friends.doc(" 2348******").collection("Friends").get().then((value) {
  for (var element in value.docs) {
    dataList.add(element.data());
  }
  dataList.forEach((element){
    if(element['name'] == " 2348******"){
      //print
    }
  })
});

CodePudding user response:

I think you should try this code... Hopefully, it goes well... works with normal map at the moment.

List<Map> dataList = [];
    await friends.doc(" 2348******").collection("Friends").get().then((value) {
      for (var element in value.docs) {
        dataList.add(element.data());
      }

    //Try this code
      var key = dataList.keys.firstWhere((k)
          => countries[k] == ' 23789900', orElse: () => null);

    print(key); //output: 35

    });
  • Related