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

标签 csv flutter dart dart-pub

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

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);
}

如何将这些数据从 csv 文件转换为 类食品裁剪一览 ?
List<foodCrops> 

最佳答案

在这里,我只是解析这些行以制作 FoodCrop 的实例类(class)。您可以根据需要解析数据。

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}';
  }
}

关于csv - Dart:如何将 CSV 数据映射到模型列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079848/

相关文章:

java - 从csv文件读取的字符串不等于java中定义的字符串代码

dart - Flutter - 设置小部件的比例

firebase - 为什么我的 flutter 应用程序在我的设备离线时在 firestore 上保存了两次?

python - 对 CSV 文件中的每四个元素求平均值

SQl 输出到 CSV(不带单引号)

powershell - 在 Azure datalake 中附加 csv 文件

json - Flutter 如何根据 JSON API 的状态更改颜色

flutter - 如何在 flutter 中激活/选中复选框后保持边框

dart - 如何修复 flutter 中 firestore 的事务错误?

flutter - 如何在Flutter中制作下雨动画