This dart pad is a sample code to group List of Objects based on an attribute of the list.
Last active
March 18, 2023 13:08
-
-
Save smc181002/1bb4de088c32c0034898f219438f159f to your computer and use it in GitHub Desktop.
groupby-list-of-objects
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
import "package:collection/collection.dart"; | |
import 'package:intl/intl.dart'; | |
class PayRecord { | |
String name; | |
String type; | |
String reason; | |
double amount; | |
DateTime date; | |
PayRecord(this.name, this.type, this.reason, this.amount, this.date); | |
@override | |
String toString() { | |
return '{$name, $type, $reason, $amount}'; | |
} | |
} | |
Map<String, List<PayRecord>> groupPayRecordByDate(List<PayRecord> payRecord) { | |
final groups = groupBy(payRecord, (PayRecord pr) { | |
return DateFormat.yMd().format(pr.date); | |
}); | |
return groups; | |
} | |
void main() { | |
var objData = [ | |
PayRecord("Srinu", "owes you", "", 24.0, DateTime(2023, 1, 10)), | |
PayRecord("Srinu", "you owe", "", 24.0, DateTime(2023, 1, 10)), | |
PayRecord("Vivek", "you owe", "", 24.0, DateTime(2023, 1, 11)), | |
PayRecord("Shobhit", "owes you", "", 24.0, DateTime(2023, 1, 11)), | |
]; | |
var newObjData = groupPayRecordByDate(objData); | |
print(newObjData); | |
// print(newObjData["2023-01-10 00:00:00.000"]?.first.amount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment