Flutter - How to count data based on ID in List

Viewed 18254

I have a List<Comment> from all foods.

[
 {
   comment_id: '...'
   food_id: '...'
   comment: '...'
 }, 
 {
   comment_id: '...'
   food_id: '...'
   comment: '...'
 },

  ....

]

I want to know how to count the number of comments based on food_id in Flutter? Any answer is very helpful.

2 Answers

You can use where(...) to filter a list and .length the get the result length.

var comments = <Comment>[...];
var count = comments.where((c) => c.product_id == someProductId).length;

This code will iterate over the comments and obtain the number of comments which are about the product_id_param specified.

int number_of_comments = comments.fold(
    0,
    (sum, comment) => (comment.product_id == product_id_param) ? sum + 1 : sum
);
Related