Read/Write CSV in flutter web

Kaival Patel
3 min readJan 31, 2021

--

Hello folks, this is my first story on medium, any suggestions are welcome.

Now lets jump to the story, Today we will see how I Implemented csv read/write in my flutter project, mainly on flutter web.

So let’s get started…..

yeah lets go
yeah

First things first, lets import the famous csv package into our pubspec.yaml

dependencies:  
flutter:
sdk: flutter
csv: ^4.1.0
file_picker: ^2.1.4

Please refer the latest version for csv and file picker, as of writing this article, these are the latest versions for both.

Writing csv file and downloading in flutter web is easy, lets see it now.

void main(){//your code.....//from somewhere in the code or on btn pressedgenerateCSV();
}

We made a method called generateCSV() which will handle writing of the csv file and getting downloaded afterwards.

Now inorder to generate the csv, we need to take 2D array as we have to handle list into a list i.e to handle rows and columns. I know this sounds bit confusing but you will understand in the coding part.

Writing CSV

void generateCSV(){ // we will declare the list of headers that we want
static List<String> rowHeader = ["Name","Address","Phone"];
// here we will make a 2D array to handle a row
List<List<dynamic>> rows = [];
//First add entire row header into our first row
rows.add(rowHeader);
//Now lets add 5 data rows
for(int i=0;i<5;i++){
//everytime loop executes we need to add new row
List<dynamic> dataRow=[];
dataRow.add("NAME :$i");
dataRow.add("ADDRESS :$i");
dataRow.add("PHONE:$i");
//lastly add dataRow to our 2d list
rows.add(dataRow);
}
//now convert our 2d array into the csvlist using the plugin of csv
String csv = const ListToCsvConverter().convert(rows);
//this csv variable holds entire csv data
//Now Convert or encode this csv string into utf8
final bytes = utf8.encode(csv);
//NOTE THAT HERE WE USED HTML PACKAGE
final blob = html.Blob([bytes]);
//It will create downloadable object
final url = html.Url.createObjectUrlFromBlob(blob);
//It will create anchor to download the file
final anchor = html.document.createElement('a') as html.AnchorElement..href = url..style.display = 'none' ..download = 'yourcsvname.csv';
//finally add the csv anchor to body
html.document.body.children.add(anchor);
// Cause download by calling this function
anchor.click();
//revoke the object
html.Url.revokeObjectUrl(url);

}

It will download the csv file to the device from the web

Output

Now lets see the read process

Read Process is exactly reverse of what we have created above. We will read csv file in simple format. You can enhance it by adding csv data to datatable.

Reading CSV

Here for this example, I assumed that the header row can be static or else you can make dynamic.

Importing CSV and converting to 2D Array

void importCSV(){ //Pick file
FilePickerResult csvFile =
await FilePicker.platform.pickFiles(allowedExtensions: ['csv'], type: FileType.custom,allowMultiple: false);
if(csvFile!=null){ //decode bytes back to utf8
final bytes = utf8.decode(csvFile.files[0].bytes);
//from the csv plugin List<List<dynamic>> rowsAsListOfValues = const CsvToListConverter().convert(bytes);
}
}

Now after importing the file we have decoded bytes to utf8 and then with the csv plugin bytes are converted to 2D array.

You can check for the various validation for the csv. In this article, I will put things as simple as I can.

for(int i=0;i<rowsAsListOfValues.length();i++){//inside the 2nd dimension
for (int j = 0; j < rowsAsListOfValues.elementAt(i).length; j++) { //NAME
Text("${(rowsAsListOfValues.elementAt(i).elementAt(0)});
//ADDRESS Text("${(rowsAsListOfValues.elementAt(i).elementAt(1).toString()});
//PHONE
Text("${(rowsAsListOfValues.elementAt(i).elementAt(2).toString()}); }
}

It will print the text widget of Name, address and phone. Surely you can enhance it by adding row or whatsoever widget fits in your code.

That’s it for now, hope you have learned importing exporting csvs in flutter web.

--

--

Kaival Patel

Co-founder at Devkrest Technologies, Ex Scientist Intern (ISRO)