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