fluttercsvdartfilestore

how to save data on csv file with flutter?


I have data come from a device to my flutter application via bluetooth. I have lists that are displayed one by one on alerts. I want to collect data on all the alerts and then save it on csv file. The problem is that there are lot of files created and every file contain juste one list this mean that for every alert there is a file created. this is the code:

setupMode.generateCsv((message) async {
      List<List<String>> data = [
        ["No.", "X", " Y", "Z", "Z"],
        [message.data[1], message.data[2], message.data[3], message.data[4]],
      ];

      String csvData = ListToCsvConverter().convert(data);
      final String directory = (await getApplicationSupportDirectory()).path;
      final path = "$directory/csv-${DateTime.now()}.csv";
      print(path);
      final File file = File(path);
      await file.writeAsString(csvData);
      print("file saved");
      print(csvData.length);
    });
  }

I want to collect all the data and store it on one file.


Solution

  • In order to write into one file, there are two things you need to change:

    File name:

    final path = "$directory/csv-${DateTime.now()}.csv";
    

    This creates a new file every time you call it. You should use the same file name, e.g.:

    final path = "$directory/csv-alert-data.csv";
    

    The second change is the write type:

    await file.writeAsString(csvData,mode:FileMode.append);
    

    This will append the new data to the end of the existing CSV file.