Dart: How to map CSV data to a list of a model?

2,136

Solution 1

Here, I am just parsing the lines to make instances of FoodCrop class. You can parse data as you like.

void main() {
  var foodCrops = makeFoodCropList();
  for (var foodCrop in foodCrops) {
    print(foodCrop);
  }
}

List<FoodCrop> makeFoodCropList() {
  var lines = [
    'id,cropType,cropName',
    '1,food,rice',
    '2,cash,sugarcane',
    '3,horticulture,orange',
  ];
  lines.removeAt(0); //remove column heading

  /*
  * you can use any parser for csv file,
  *
  * a csv package is available
  * or simple file reading will also get the job done main logic is coded here
  * */

  var list = <FoodCrop>[];
  for (var line in lines) list.add(FoodCrop.fromList(line.split(',')));

  return list;
}

class FoodCrop {
  int id;
  String cropType;
  String cropName;

  FoodCrop(this.id, this.cropType, this.cropName);

  FoodCrop.fromList(List<String> items) : this(int.parse(items[0]), items[1], items[2]);

  @override
  String toString() {
    return 'FoodCrop{id: $id, cropType: $cropType, cropName: $cropName}';
  }
}

Solution 2

The simplest way would probably be to read the file as a list of lines and then use map to perform the conversion.

final crops = File.readAsLinesSync('path/to/crops.csv')
                  .skip(1) // Skip the header row
                  .map((line) {
                    final parts = line.split(',');
                    return FoodCrops(
                      int.tryParse(parts[0]),
                      parts[1],
                      parts[2],
                    );
                  )
                  .toList();
Share:
2,136
Shunjid Rahman
Author by

Shunjid Rahman

I love building web applications and web API using .NET Core, designing web pages with material design frameworks and analyzing data for statistical representations. Programming is my passion and I love to solve real life problems in programming. Usually, I work in Ubuntu. I want to be a Software Engineer in Microsoft one day.

Updated on December 01, 2022

Comments

  • Shunjid Rahman
    Shunjid Rahman over 1 year

    Let's say, In a file crops.csv, I have a simple dataset in a format like this:

    id,cropType,cropName
    1,food,rice
    2,cash,sugarcane
    3,horticulture,orange
    

    And I have a Model Class named as foodCrops:

    class foodCrops {
      int id;
      String cropType;
      String cropName;
    
      foodCrops(this.id, this.cropType, this.cropName);
    }
    

    How do I convert those data from csv file to a List of class foodCrops ?

    List<foodCrops>