-1

This is the current state of the Map data structure that I am working with in Dart:

Map database = {
    'campusConnect': {
        'hashtags': [
             {
                 'id': 4908504398, 
                 'title': '#NeverGiveUp!', 
                 'author': 'ABC',  
             }, 
             {
                  'id': 430805, 
                 'title': '#ItAlwaysTakesTime', 
                 'author': 'XYZ'
             }
         ]
     }
};

I want to go over the hashtags array. Iterating over each object in that array, I want to compare the 'id' field with some number that I already have. How do I do it?

So far, this is what I have tried doing:

database['campusConnect']['hashtags'].map( (item) {
    print('I am here ...');
    if (item['id'] == hashtagId) {
        print(item['title']);
    }
});

I have no idea why, but it gives me no error and does not work at the same time. When I run it, it does not even print "I am here ...".

Notice the identifier "hashtagId" in the if block:

if (item['id'] == hashtagId) { ... }

This is being passed in the function as an argument. For simplicity, I have not show the function, but assume that this is an int-type parameter I am receiving

How should I accomplish this?

John Doe
  • 87
  • 1
  • 9
  • try `(database['campusConnect']['hashtags'] as List).map( (item) {...}` and wrap that inside a try catch to start seeing the errors. Let us try to get more info – croxx5f Jul 14 '21 at 22:06
  • This is your real code? If so, you defined `hashTags` in the map and `hashtags` when calling the map – Lucas Josino Jul 14 '21 at 22:08
  • @croxx5f still the problem persists. It does not even print "I am here ...." – John Doe Jul 14 '21 at 22:13

2 Answers2

1

Dart is smart enough to skip the code that does nothing. In your case, you are not using the result of map() function. Try to change it with forEach() and fix hashTags typo

  database['campusConnect']['hashTags'].forEach((item) {
    print('I am here ...');
    if (item['id'] == hashtagId) {
      print(item['title']);
    }
  });
Yuri H
  • 680
  • 5
  • 12
0

The following method will solve your question.

  void test(){
    final hashTags = database['campusConnect']['hashTags'];
    if(hashTags is List){
      for(var i=0; i<hashTags.length; i++){
        final id = hashTags[i]['id'];
        if(id == hashtagId){
          // do something
        }
      }
    }
  }
Salih Can
  • 1,562
  • 1
  • 9
  • 18