4

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> 
Shunjid Rahman
  • 409
  • 5
  • 17

3 Answers3

7

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}';
  }
}
Doc
  • 10,831
  • 3
  • 39
  • 63
5

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();
Abion47
  • 22,211
  • 4
  • 65
  • 88
0

Another way to do that.

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final list = data.skip(1).map((e) => FoodCrops(int.parse(e[0]), e[1], e[2]));
  print(list.join('\n'));
}

const _source = '''
id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
''';

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

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

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

Output:

1 food rice
2 cash sugarcane
3 horticulture orange
mezoni
  • 10,684
  • 4
  • 32
  • 54