skip to Main Content

Using map.entries property i want to fetch all values those are even in a map data,

I have any other solutions to get this output but i want it to solve it with map.entries property…

its return null when value is not even

output should be [2,4] instead of [null,2,null,4]

void main() {
  final  myMap={
    'first':1,
    'second':2,
    'three':3,
    'four':4,
  };

  List<dynamic> list=[];

  list=myMap.entries.map((e) {
    if(e.value%2==0)
    return e.value;
    
  }).toList();
  print(list);



}

2

Answers


  1. Try below code and try to use where condition/method to filter out null values

    void main() {
      final myMap = {
        'first': 1,
        'second': 2,
        'three': 3,
        'four': 4,
      };
    
     
      List<dynamic> list = myMap.entries
          .map((e) => e.value % 2 == 0 ? e.value : null)
          .where((value) => value != null)
          .toList();
    
      print(list); 
    }
    

    Read where method

    Login or Signup to reply.
  2. Is there a reason why you specifically want to use entries? Surely using values seems better. Then you can do

    list = myMap.values.where((e) => e % 2 == 0).toList()
    

    If you insist on entries then do it like

    list = myMap.entries.where((e) => e.value % 2 == 0).map((e) => e.value).toList()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search