how to convert List<Model> to custom data in dart?

Is there any easy way convert List to other model data?

this is my model:

class Account {
  String name;
  double balance;

  Account({required this.name, required this.balance});
}

class CategoryAccount {
  String type;
  List<Account> items;

  CategoryAccount({required this.type, required this.items});
}

this is sourceData:

List<Account> sourceData = [
  Account(name: 'cash', balance: 100),
  Account(name: 'cash', balance: 200),
  Account(name: 'bank', balance: 300),
  Account(name: 'creditor', balance: 400),
];

I want sourceData convert to finalData:

List<CategoryAccount> finalData = [
  CategoryAccount(
    type: 'cash',
    items: [
      Account(name: 'cash', balance: 100),
      Account(name: 'cash', balance: 200),
    ],
  ),
  CategoryAccount(
    type: 'bank',
    items: [
      Account(name: 'bank', balance: 300),
    ],
  ),
  CategoryAccount(
    type: 'creditor',
    items: [
      Account(name: 'creditor', balance: 300),
    ],
  ),
];

In Dart I saw the following method for a List : asMap(), but it’s not doing what i expect: it use the list index as key. My questions:

Do you known anything in Dart libraries to do this ?

>Solution :

Solution without using a package:

List<CategoryAccount> finalData = [];

for (var se in sourceData) {
  final index = finalData.indexWhere((fe) => fe.type == se.name);
  if (index >= 0) {
    finalData[index].items.add(se);
  } else {
    finalData.add(CategoryAccount(type: se.name, items: [se]));
  }
}

Explanation:

  • Line 3: Loop through each elements in the sourceData variable
  • Line 4: Finding the index/position of the CategoryAccount object where the
    type matches with the element name
  • Line 6: Adding the item to the
    existing CategoryAccount object if match found (step 4)
  • Line 8: Else,
    create a new CategoryAccount and add the current element

Leave a Reply