Flutter CSV Reader

Last Updated On Monday 1st Nov 2021

What is a CSV ?

  • CSV –> Comma Separated Values
  • It is a simple file format used to store tabular data, such as a spreadsheet/excel or database.
  • CSV is convenient way to export data to spreadsheets and databases as well as import or use it in other programs.

Flutter CSV Reader Web

	 List<List> finalContent = [];
 List CsvModuleList = [];

  PlatformFile selectedOne ;
  Future selectCSVFile() async {
    FilePickerResult res = await FilePicker.platform.pickFiles(
        allowMultiple: false,
        withData: true,
        type: FileType.custom,
        allowedExtensions: ['csv']);

    if (res != null) {
      selectedOne = res.files.first;
      parseCSV();
      return;
    } else {
      selectedOne = null;
    }
  }

  void parseCSV () async {
    try {
      String str = new String.fromCharCodes(selectedOne.bytes);
      var decodeList = new Uint8List.fromList(str.codeUnits);
      contentList = utf8.decode(decodeList).split('\n');
      contentList.forEach((element) {
        List currentRow = [];
        element.toString().split(",").forEach((items) {
          currentRow.add(items.trim());
        });
        setState(() {
          finalContent.add(currentRow);
        });
      });

    // check if CSV file has any content - content length > 0?
      if (contentList.length == 0 || contentList[1].length == 0) {
        // CSV file does not have content
        print('CSV file has no content');
      }
    } catch (e) {
      print(e.toString());
    }
  }