Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart CSV Writing

Tags:

csv

flutter

dart

Hey so I haven't really messed around with it too much, but I was wondering if there was actually a way (before I go down a neverending rabbit hole) to read and write to CSV files in Dart/Flutter? I need to write to the files, not necessarily read them, and I'm willing to go to quite extreme lengths to do so. Any library works, built-in functions are even better. Any and all help is appreciated!

like image 512
Lloyd7113 Avatar asked Oct 20 '25 12:10

Lloyd7113


2 Answers

Use package csv from https://pub.dartlang.org/packages/csv

If you have a List<List<dynamic>> items that needs to convert into csv,

String csv = const ListToCsvConverter().convert(yourListOfLists);

If you want to write the csv to a file,

/// Write to a file
final directory = await getApplicationDocumentsDirectory();
final pathOfTheFileToWrite = directory.path + "/myCsvFile.csv";
File file = await File(pathOfTheFileToWrite);
file.writeAsString(csv);    

Also, if you want to read a csv file directly into list<list<dynamic>>

final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(UTF8.decoder).transform(csvCodec.decoder).toList();
like image 195
krishnakumarcn Avatar answered Oct 23 '25 03:10

krishnakumarcn


According to new packages and guidelines(2019) use following code

package csvfrom https://pub.dartlang.org/packages/csv.

If you have a List<List<dynamic>> items that needs to convert into csv,

String csv = const ListToCsvConverter().convert(yourListOfLists);

Then you can write the string to a file using file operations.

file.writeAsString('$csv');

Also, if you want to read a csv file directly into list<list<dynamic>>

final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();
like image 25
Adnan Kazi Avatar answered Oct 23 '25 02:10

Adnan Kazi