CSV
suggest changeComma-Separated Values (CSV) is a standard format for tabular data exchange across databases, spreadsheets, and data processing pipelines. In Dart and Flutter applications, the standard package for parsing and generating CSV files is csv.
Installing the csv Package
Add csv to your pubspec.yaml:
dependencies:
csv: ^6.0.0
Run dart pub get to download the package.
This article uses the 6.x API (ListToCsvConverter, CsvToListConverter). Version 7.0 of the package was a complete rewrite with a different API, so keep the ^6.0.0 constraint if you follow these examples.
Generating CSV from Lists
To convert an in-memory table (a list of lists) into a CSV formatted string, use ListToCsvConverter:
import 'package:csv/csv.dart';
void main() {
final data = [
['ID', 'Name', 'Role', 'Salary'],
[101, 'Alice Smith', 'Lead Engineer', 125000],
[102, 'Bob Jones, Jr.', 'Product Manager', 110000],
[103, 'Charlie "Chuck" Brown', 'Designer', 95000],
];
// Convert to standard CSV string
final csvString = const ListToCsvConverter().convert(data);
print(csvString);
}
Output:
ID,Name,Role,Salary
101,Alice Smith,Lead Engineer,125000
102,"Bob Jones, Jr.",Product Manager,110000
103,"Charlie ""Chuck"" Brown",Designer,95000
Notice that fields containing commas or quotes are automatically quoted and escaped according to RFC 4180.
Parsing CSV Strings
Use CsvToListConverter to decode CSV text into rows of values:
import 'package:csv/csv.dart';
void main() {
const csvData = '''
sku,name,price,in_stock
A101,Wireless Mouse,29.99,true
B202,Mechanical Keyboard,89.50,false
C303,"Monitor 27""",199.00,true
''';
// Decode into List<List<dynamic>>
final rows = const CsvToListConverter(eol: '\n').convert(csvData);
// Extract header and data rows
final headers = rows.first;
final dataRows = rows.skip(1);
print('Headers: $headers');
for (final row in dataRows) {
final sku = row[0] as String;
final name = row[1] as String;
final price = (row[2] as num).toDouble();
final inStock = row[3] == 'true'; // booleans are not converted
print('$sku: $name costs \$$price (In stock: $inStock)');
}
}
Output:
Headers: [sku, name, price, in_stock]
A101: Wireless Mouse costs $29.99 (In stock: true)
B202: Mechanical Keyboard costs $89.5 (In stock: false)
C303: Monitor 27" costs $199.0 (In stock: true)
Mapping Rows to Domain Models
Mapping CSV rows into strongly typed Dart classes provides compile-time safety:
import 'package:csv/csv.dart';
class Employee {
final int id;
final String name;
final String department;
Employee({required this.id, required this.name, required this.department});
factory Employee.fromCsvRow(List<dynamic> row) {
return Employee(
id: row[0] as int,
name: row[1] as String,
department: row[2] as String,
);
}
List<dynamic> toCsvRow() => [id, name, department];
}
void main() {
const rawCsv = '101,Diana Prince,Engineering\n102,Bruce Wayne,Management';
final rows = const CsvToListConverter(eol: '\n').convert(rawCsv);
final employees = rows.map((r) => Employee.fromCsvRow(r)).toList();
for (final emp in employees) {
print('${emp.name} works in ${emp.department}');
}
}
Custom Delimiters (TSV and Semicolons)
You can customize delimiters for Tab-Separated Values (TSV) or European CSV files that use semicolons:
import 'package:csv/csv.dart';
void main() {
final data = [
['SKU', 'Description', 'Price'],
['P01', 'Espresso, Roast', '4,50'],
];
// Semicolon delimited with comma decimal separator
final customCsv = ListToCsvConverter(
fieldDelimiter: ';',
textDelimiter: '"',
eol: '\r\n',
).convert(data);
print(customCsv);
}
Streaming Large CSV Files (Low Memory Usage)
When dealing with large CSV files (hundreds of megabytes), reading the entire file into memory with readAsString() can cause memory spikes. Instead, stream the file in chunks using dart:io and CsvToListConverter. Don't split the text with LineSplitter first: the converter needs the line endings to find row boundaries, and quoted fields can contain newlines:
import 'dart:convert';
import 'dart:io';
import 'package:csv/csv.dart';
Future<void> processLargeCsv(String filePath) async {
final file = File(filePath);
final stream = file
.openRead()
.transform(utf8.decoder)
.transform(const CsvToListConverter(eol: '\n'));
int rowCount = 0;
await for (final row in stream) {
rowCount++;
if (rowCount == 1) continue; // Skip header
// Process single row incrementally
}
print('Processed $rowCount rows without buffering entire file in memory.');
}
Best Practices
- Specify
eolexplicitly: Operating systems use different line endings (\non Linux/macOS,\r\non Windows). Settingeol: '\n'oreol: '\r\n'prevents unexpected row splitting. - Always handle dynamic types defensively:
CsvToListConverterinfers numbers (int,double) automatically, but everything else (includingtrue/false) stays aString. Cast using(row[index] as num).toDouble()to avoid type errors. - Stream large files: Use
openRead().transform(...)for files exceeding a few megabytes to keep memory usage minimal.