Reputation: 708
I have a chats class:
List<Message> chats = [
Message(
sender: roberta,
time: '5:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
),
Message(
sender: roberta,
time: '5:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
),
Message(
sender: stefano,
time: '4:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
),
With messages property and one of them is "unread" property. How I can assign true to an Int like a number 1 and if is false is 0 I need to take this bool "unread" and transform into a number to show how many unreads message into a notification widget in flutter
Any input?
Upvotes: 2
Views: 963
Reputation: 4068
I think this is what you need.
List<Messages> x = [
Messages("asdg", true),
Messages("dagd", false),
Messages("asdg", true)
];
print(x
.map<int>((element) => element.read ? 1 : 0)
.fold<int>(0, (previous, obj) => previous + obj));
For efficiency purposes though, if this is a chat app. You should be subscribed to some kind of Stream and only save a counter which you increment if there onChanged is triggered by your listener.
Upvotes: 2
Reputation: 6776
Try This
class Message {
String sender;
String time;
String text;
bool isLiked;
bool unread;
Message({this.sender= "",
this.time = "",
this.text= "",
this.isLiked= false,
this.unread= false });
}
void main() {
List<Message> chats = [
Message(
sender: "roberta",
time: '5:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
),
Message(
sender: "roberta",
time: '5:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
),
Message(
sender: "stefano",
time: '4:30 PM',
text: 'Hey, how\'s it going? What did you do today?',
isLiked: false,
unread: true,
)
];
int unreadCount=0;
for (int i = 0; i < chats.length; i++) {
if(chats[i].unread)
unreadCount++;
}
print(" Total Unread messages :"+ unreadCount.toString());
}
OR use folds like this
int cnt=0;
chats.fold(0, (t, e) => (e.unread?cnt++:0));
print(" Total Unread messages :"+ cnt.toString());
Upvotes: 1