Dart:如何将 CSV 数据映射到模型列表?

Shu*_*man 3 csv dart dart-pub flutter

比方说,在文件crop.csv 中,我有一个格式如下的简单数据集:

id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
Run Code Online (Sandbox Code Playgroud)

我有一个名为foodCrops的模型类:

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

  foodCrops(this.id, this.cropType, this.cropName);
}
Run Code Online (Sandbox Code Playgroud)

如何将这些数据从 csv 文件转换为类 foodCrops列表

List<foodCrops> 
Run Code Online (Sandbox Code Playgroud)

Doc*_*Doc 6

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}';
  }
}
Run Code Online (Sandbox Code Playgroud)


Abi*_*n47 5

最简单的方法可能是将文件作为行列表读取,然后用于map执行转换。

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();
Run Code Online (Sandbox Code Playgroud)