Read And Write CSV File In Flutter(Web, Mobile)

Published by Abhay Rastogi on

CSV file flutter

In Flutter, you can read and write CSV files. We must ensure a couple of things. The most important aspect of reading the CSV file is loading it into Flutter, and for that, we can use the file picker plugin, which assists us in selecting the CSV file. We will also use the CSV plugin to write CSV files, and the url launcher plugin to download CSV files.

Plugins Summery

Flutter read CSV file from locally and assets.

To read the CSV file, we must first select it from the web’s local folder or the phone’s assets folder. it will come in handy by using the flutter file_picker plugin as soon below.

import 'package:file_picker/file_picker.dart;

PlatformFile selectedFile;
Future selectCSVFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
        allowMultiple: false,
        withData: true,
        type: FileType.custom,
        allowedExtensions: ['csv']);
    
    if (result != null) {
      selectedFile = result.files.first;
    } else {
      selectedFile = null;
    }

}

Now we have read the file which is picked by the file picker and later manipulate the data using the class module and convert it into JSON format.


List csvList;
List csvFileContentList = [];
List CsvModuleList = [];

// Select and Parse the CSV File
Future<String> selectParseCSV() async {

//Optional for CSV Validation
String csvFileHeaderRowColumnTitles =
      'Field1,Field2'; 

try{
     String s = new String.fromCharCodes(selectedCSVFile.bytes);
        // Get the UTF8 decode as a Uint8List
        var outputAsUint8List = new Uint8List.fromList(s.codeUnits);
        // split the Uint8List by newline characters to get the csv file rows
        csvFileContentList = utf8.decode(outputAsUint8List).split('\n');
        print('Selected CSV File contents: ');
        print(csvFileContentList);
  
 // Check the column titles and sequence - is the CSV file in the correct template format?
        if (csvFileContentList[0].toString().trim().hashCode !=
            csvFileHeaderRowColumnTitles.hashCode) {
          // CSV file is not in correct format
          print('CSV file does not seem to have a valid format');
          return 'Error: The CSV file does not seem to have a valid format.';
        }
 
// Check the column titles and sequence - is the CSV file in the correct template format?
        if (csvFileContentList[0].toString().trim().hashCode !=
            csvFileHeaderRowColumnTitles.hashCode) {
          // CSV file is not in correct format
          print('CSV file does not seem to have a valid format');
          return 'Error: The CSV file does not seem to have a valid format.';
        }

// check if CSV file has any content - content length > 0?
        if (csvFileContentList.length == 0 ||
            csvFileContentList[1].length == 0) {
          // CSV file does not have content
          print('CSV file has no content');
          return 'Error: The CSV file has no content.';
        }
        // CSV file seems to have a valid format
        print(
            'CSV file has a valid format and has contents, hence proceed to parse...');

// Current First row of the CSV file has column headers - remove it
        csvFileContentList.removeAt(0);
        print('Selected CSV File contents after removing the Column Headers: ');

// Remove Duplicate Rows from the CSV File
        csvList = csvFileContentList.toSet().toList();
        print('CSV file contents after deduplication / removal of duplicates');
     //CSV Files in Array  
     print(csvList);

//Array to class module
csvList.forEach((csvRow) {
 if (csvRow != null && csvRow.trim().isNotEmpty) {
            // current row has content and is not null or empty
CsvModuleList.add(CsvModuleList.fromList(csvRow.split(','));
}
});


}catch (e) {
        print(e.toString());

        return 'Error: ' + e.toString();
 }

CsvModuleList.forEach((data){
    print(data.toList());
    print(data.toJson());
});

}

CsvModule


class CsvModule{
  
  final String field1; 
  final String field2;
  CsvModule(
      {this.field1 = '',
      this.field2 = '',});
   
  // List to class Module
  CsvModule.fromList(List items)
      : this(
          field1: items[0].trim(),
          field2: items[1].trim());
  
 // Convert Data to JSON 
  Map toJson() {
    return {
      'fieldOne': field1,
      'fieldTwo': field2
     };
   }
  
  // Convert Data to list
  List toList() {
    return [
      field1,
      field2,];
  } 
 
  // JSON to class Module
  factory CsvModule.fromData(Map data) {
    return CsvModule(
        field1: data['fieldOne'],
        field2: data['fieldTwo']);
  }

}

Write or create CSV file in a flutter

For writing or creating CSV file convert the List to CSV file by using CSV plugin.

import 'package:csv/csv.dart';

  String csv;
  Future createCSVFile() async {
  List<List<dynamic>> csvList = [];      
  csvList.add(csvHeaderTitle);
    

    for (var data in CsvModuleList.toSet()) {
      
     List row = [];
      row.add(data.toJson()['FieldOne']);
      row.add(data.toJson()['FieldTwo']);
      

      csvList.add(row);
    }

    csv = const ListToCsvConverter().convert(csvList);
    
    print(CSV);
  }

Download CSV

Download the the CSV file by using url_launcher plugin.

import 'package:url_launcher.dart

void downloadCSV(){
    final content = base64Encode(csv.codeUnits);
    final url = 'data:application/csv;base64,$content';
    await UrlLauncherPlugin().launch(url);
}

Categories: flutter

2 Comments

Santhosh Ramachandran · 26th June 2021 at 4:14 pm

Thank you for this article, it helped me. Although the file downloaded is not with extension of .csv . Do you know how to fix it

    Abhay Rastogi · 27th June 2021 at 11:05 am

    void downloadCSV(){
    final content = base64Encode(csv.codeUnits);
    final url = ‘data:application/csv;base64,$content’;
    await UrlLauncherPlugin().launch(url);
    }

Leave a Reply

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