0

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?

3
  • 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 Commented Jul 14, 2021 at 22:06
  • This is your real code? If so, you defined hashTags in the map and hashtags when calling the map Commented Jul 14, 2021 at 22:08
  • @croxx5f still the problem persists. It does not even print "I am here ...." Commented Jul 14, 2021 at 22:13

2 Answers 2

0

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']);
    }
  });
Sign up to request clarification or add additional context in comments.

Comments

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
        }
      }
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.