Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 934
Muhammad Imanudin Avatar asked Dec 10 '22 04:12

Muhammad Imanudin


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;
like image 158
Günter Zöchbauer Avatar answered Jan 31 '23 07:01

Günter Zöchbauer


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
);
like image 24
Martyns Avatar answered Jan 31 '23 06:01

Martyns