Home > Back-end >  Not able to write to an exisitng file in Flutter
Not able to write to an exisitng file in Flutter

Time:08-10

I am trying to overwrite the contents of a CSV file in my app_name/assets/file.csv path. I'm using path_provider and csv for these operations.

Here's the code that is supposed to write to the existing CSV file:

updateQuantity(customer, index, qty, list) async {
    list[index][2] = qty;
    String updatedCsv = const ListToCsvConverter().convert(list);
    print(updatedCsv);

    final dir = await getApplicationDocumentsDirectory();
    String path = "${dir.path}/assets/$customer.csv";

    File file = await File(path);
    file.writeAsString(updatedCsv);
  }

The error I receive:

E/flutter ( 4352): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.data_collection_2/app_flutter/assets/Test.csv' (OS Error: No such file or directory, errno = 2)

I have scoured the internet but nothing seems to be helping me write to the file.

Thanks in advance

CodePudding user response:

Are you sure that the directory assets already exists? If the CSV does not already exist then it will fail since the directory assets probably does not exist either.

The way to fix this is to do File file = await File(path).create(recursive: true);.

This will create the file and the directory assets if they do not already exist. If they do exist it will do nothing and will not fail so it is safe either way.

  • Related