Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading