You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart/Flutter中如何将CSV解析的List<List<dynamic>>映射为可点调用对象

Dart/Flutter CSV数据点语法访问实现方案

两种低成本实现方案,不需要全量手动编码:

方案1:扩展方法实现(零改造成本,代码量最少)

直接给CSV单行的List<dynamic>类型加扩展getter,不需要修改原有数据结构,每个字段仅需写1行代码:

// 全局声明扩展,引入后即可直接使用
extension CsvTimeRecord on List<dynamic> {
  String get id => this[0].toString();
  String get startTime => this[1].toString();
  String get lap1 => this[2].toString();
  String get lap2 => this[3].toString();
  String get lap3 => this[4].toString();
  // 新增字段直接按照索引加对应getter即可
}

使用示例:

// 原有查找逻辑完全不用改
final targetIndex = _listData.indexWhere((element) => element.first == 2);
final myTimes = _listData[targetIndex];
// 直接用点语法访问
print(myTimes.startTime); // 输出 01:05
print(myTimes.lap1); // 输出 01:10

方案2:模型类实现(类型安全,推荐生产环境用)

如果需要编译期类型校验,避免索引写错导致的运行时崩溃,写个极简模型类加工厂构造即可:

class TimeRecord {
  final String id;
  final String startTime;
  final String lap1;
  final String lap2;
  final String lap3;

  const TimeRecord({
    required this.id,
    required this.startTime,
    required this.lap1,
    required this.lap2,
    required this.lap3,
  });

  // 只需要写一次转换逻辑
  factory TimeRecord.fromCsvRow(List<dynamic> row) {
    return TimeRecord(
      id: row[0].toString(),
      startTime: row[1].toString(),
      lap1: row[2].toString(),
      lap2: row[3].toString(),
      lap3: row[4].toString(),
    );
  }
}

使用示例:

// 拿到CSV原始数据后一次性转换为模型列表
List<TimeRecord> recordList = _listData.map((row) => TimeRecord.fromCsvRow(row)).toList();
// 查找直接操作模型
final myTimes = recordList.firstWhere((record) => record.id == '2');
print(myTimes.startTime);

如果字段量级极大(超过20个),可使用Dart官方代码生成工具自动生成映射逻辑,不需要手动逐个写字段映射。


内容的提问来源于stack exchange,提问作者mfaiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:18:00