Created with <3 with dartpad.dev.
Created
January 19, 2024 06:17
-
-
Save matifdeveloper/fe105241279559aa6916ca32c5bbdaaf to your computer and use it in GitHub Desktop.
Last and Unique 4 valuse in List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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