'Flutter - How to count data based on ID in List [closed]

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.



Solution 1:[1]

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;

Solution 2:[2]

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
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Martyns