Schema, validation and coercion
Say what each column should be, then check it or convert it.
Install#
dart pub add csv_plusimport 'package:csv_plus/csv_plus.dart';Declare the columns#
final schema = CsvSchema(columns: [
CsvColumnDef(name: 'email', type: String, required: true, pattern: r'@'),
CsvColumnDef(name: 'age', type: int, nullable: false),
]);Validate#
final errors = table.validate(schema); // List<CsvValidationException>
final ok = table.conformsTo(schema); // boolCoerce#
Validation tells you what is wrong. Coercion converts each column to its declared type, and fails loudly rather than guessing.
final typed = CsvCodec().decodeWithSchema('email,age\na@b.com,42', schema);
typed.rawData.first; // [a@b.com, 42] (42 is an int, not "42")
final coerced = table.coerce(schema); // or coerce a table you already haveA value that will not convert, or a null in a column marked non-nullable, throws CsvParseException carrying the row and column, so the error names the cell rather than the file.
Supported types are int, double, num, bool, String and DateTime.
Strict parsing#
Schema checking is about the values. If you also want the structure checked, turn on strict mode so malformed CSV throws instead of being recovered:
final strict = CsvCodec(CsvConfig(strict: true));