Async and Practical
CSV Parse Lite
A tiny CSV reader is just split plus a loop. The first row is the header, the rest are data rows, and a collection-for zips header names to fields to build one map per row.
Program
Play the program to parse a 3-line CSV into records and summarize them.
csv_parse_lite.dart
Replay: real traced execution (multi-file project)
void main() {
var csv = 'name,score\nAda,3\nLin,5';
var lines = csv.split('\n');
var headers = lines.first.split(',');
var rows = <Map<String, String>>[];
for (var line in lines.skip(1)) {
var fields = line.split(',');
var record = {
for (var i = 0; i < headers.length; i++)
headers[i]: fields[i],
};
rows.add(record);
}
var summary = rows
.map((r) => '${r['name']}=${r['score']}')
.join('|');
print(summary);
}
csv ← 3 lines
1void main() {2 var csv = 'name,score\nAda,3\nLin,5';3 var lines = csv.split('\n');values this step3 linescsvlines ← 3 rows
2var csv = 'name,score\nAda,3\nLin,5';3var lines = csv.split('\n');4var headers = lines.first.split(',');values this step3 rowslinesheaders ← [name, score]
3var lines = csv.split('\n');4var headers = lines.first.split(',');5var rows = <Map<String, String>>[];values this step[name, score]headersrows ← []
4var headers = lines.first.split(',');5var rows = <Map<String, String>>[];6for (var line in lines.skip(1)) {values this step[]rowsloop ← skip header, parse rows
5var rows = <Map<String, String>>[];6for (var line in lines.skip(1)) {7 var fields = line.split(',');values this stepskip header, parse rowslooprows ← [{name:Ada,score:3}, {name:Lin,score:5}]
11 };12 rows.add(record);13}values this step[{name:Ada,score:3}, {name:Lin,score:5}]rowssummary ← Ada=3|Lin=5
15 .map((r) => '${r['name']}=${r['score']}')16 .join('|');17print(summary);values this stepAda=3|Lin=5summaryprint(summary);
16 .join('|');17 print(summary);18}outputAda=3|Lin=5values this stepAda=3|Lin=5summary
split lines
`csv.split('\n')` yields one string per line; the first is the header row.
skip header
`lines.skip(1)` advances past the header so the loop sees only data rows.
zip to map
A collection-`for` over `headers` pairs each header name with the matching field.