Skip to content

Instantly share code, notes, and snippets.

@matifdeveloper
Created January 19, 2024 06:17
Show Gist options
  • Save matifdeveloper/fe105241279559aa6916ca32c5bbdaaf to your computer and use it in GitHub Desktop.
Save matifdeveloper/fe105241279559aa6916ca32c5bbdaaf to your computer and use it in GitHub Desktop.
Last and Unique 4 valuse in List

Last and Unique 4 valuse in List

Created with <3 with dartpad.dev.

class ChatsModel {
int? id;
String? title;
String chatName;
String chatType;
String icon;
bool isPinned;
ChatsModel({this.id, this.title, required this.chatName, required this.chatType, required this.icon, required this.isPinned});
}
void main() {
List<ChatsModel> chatsList = [
ChatsModel(
chatName: 'asds',
chatType: 'bot',
icon: 'dadas',
isPinned: true,
),
ChatsModel(
chatName: 'asds',
chatType: 'ok',
icon: 'dadas',
isPinned: true,
),
ChatsModel(
chatName: 'asds',
chatType: 'bot',
icon: 'dadas',
isPinned: true,
),
ChatsModel(
chatName: 'asds',
chatType: 'bot',
icon: 'dadas',
isPinned: true,
),
];
Set<String> uniqueBotChatNames = {};
List<ChatsModel> last4UniqueBotChats = [];
for (int i = chatsList.length - 1; i >= 0; i--) {
ChatsModel chat = chatsList[i];
if (chat.chatType == 'bot' && uniqueBotChatNames.add(chat.chatName)) {
last4UniqueBotChats.add(chat);
if (last4UniqueBotChats.length == 4) {
break;
}
}
}
// Now last4UniqueBotChats contains the last 4 unique elements where chatType is 'bot'
for (ChatsModel chat in last4UniqueBotChats.reversed) {
print("${chat.chatName}, ${chat.chatType}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment