How to parse CSV bytes in Flutter
File pickers, assets and HTTP responses all hand you bytes, not a path. Decode them directly.
Install#
dart pub add csv_plusimport 'package:csv_plus/csv_plus.dart';Why bytes and not a path#
On Flutter web there is no file system path to open, so file_picker gives you PlatformFile.bytes. Bundled assets arrive from rootBundle.load() as ByteData, and an HTTP body arrives as response.bodyBytes. All three are byte lists.
decodeBytes takes them directly. The byte order mark, the sep= hint and delimiter detection are all applied on the way in, exactly as they are for a string.
From a file picker#
import 'package:csv_plus/csv_plus.dart';
import 'package:file_picker/file_picker.dart';
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['csv'],
withData: true, // required on web, and convenient everywhere
);
final bytes = result?.files.single.bytes;
if (bytes != null) {
final rows = const CsvCodec().decodeBytes(bytes);
print(rows.first);
}From a bundled asset#
import 'package:flutter/services.dart' show rootBundle;
final data = await rootBundle.load('assets/products.csv');
final rows = const CsvCodec().decodeBytes(data.buffer.asUint8List());From an HTTP response#
final response = await http.get(Uri.parse('https://example.com/export.csv'));
final table = const CsvCodec().decodeBytesToTable(response.bodyBytes);
print(table.headers);Straight to maps or JSON#
decodeBytesToMaps keys every row by its header, which is most of a CSV to JSON conversion already:
import 'dart:convert';
final json = jsonEncode(const CsvCodec().decodeBytesToMaps(bytes));The full set is decodeBytes, decodeBytesWithHeaders, decodeBytesToTable and decodeBytesToMaps, mirroring the string decoders.
Writing bytes back out#
encodeToBytes returns UTF-8 bytes ready for File.writeAsBytes, a web download, or an HTTP body:
final bytes = const CsvCodec().encodeToBytes(rows);
// For a file Excel will open as UTF-8, add the byte order mark:
const forExcel = CsvCodec(CsvConfig(addBom: true));
final excelBytes = forExcel.encodeToBytes(rows);If the file is not UTF-8, see encodings.