Flutter : Create CSV file in dart

Flutter is a new cross platform mobile development framework by google. I have been developing flutters apps from a year. Recently I came across a library that helps to export the data to CSV file. Strictly speaking this type of logic should be on server side (exporting data to different file formats). There might be situation where you need to do it on client side. In such situations this plugin come in handy. In this post I will explain how to do this with CSV library.

Steps to export data to csv file from a flutter app:

  1. Add csv plugin in pubspec.yaml
  2. Import it in the dart file that handles csv file creation.
  3. For android , writeExternalStorage permission needs to be given in the manifest file
  4. ListToCsvConverter().convert(rows) is used to convert a list of items into a csv file. Here rows is of type List<List<dynamic>>, i e rows is a list of list. Inner list refer to colums of a row in csv file , and outer list refer to rows in the file.

Implementation

Consider below data set

Name     Gender      Age
Peter      Male          25
Samy     Male           32
Steve     Male           22

getCsv() is a function in dart to convert list to csv file.

getCsv() async {

 //create an element rows of type list of list. All the above data set are stored in associate list
//Let associate be a model class with attributes name,gender and age and associateList be a list of associate model class.


 List<List<dynamic>> rows = List<List<dynamic>>();
  for (int i = 0; i <associateList.length;i++) {

//row refer to each column of a row in csv file and rows refer to each row in a file
    List<dynamic> row = List();
    row.add(associateList[i].name);
    row.add(associateList[i].gender);
    row.add(associateList[i].age);
    rows.add(row);
  }

 await SimplePermissions.requestPermission(Permission. WriteExternalStorage);
  bool checkPermission=await SimplePermissions.checkPermission(Permission.WriteExternalStorage);
  if(checkPermission) {

//store file in documents folder

    String dir = (await getExternalStorageDirectory()).absolute.path + "/documents";
    file = "$dir";
    print(LOGTAG+" FILE " + file);
    File f = new File(file+"filename.csv");

// convert rows to String and write as csv file

    String csv = const ListToCsvConverter().convert(rows);
    f.writeAsString(csv);
  }


}
18 Comments

Add a Comment

Your email address will not be published. Required fields are marked *