Not able to load a file from flutter

Advertisements

I write this code to save an list as csv file

  generatecsv() async {
    if (await Permission.storage.request().isGranted) {
      String dir = (await getExternalStorageDirectory())!.path;
      String filep = "$dir/csvdatasave.csv";
      File f = new File(filep);
      String csv = const ListToCsvConverter().convert(_logdata);
      f.writeAsString(csv);
      print("gen complete");
    } else {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
      ].request();
    }
  }

It worked…and it generated the file…
But i can’t load the file to app again…
This is my code…

 _loadedCSV() async {
    if (await Permission.storage.request().isGranted) {
      String dir = (await getExternalStorageDirectory())!.path;
      String filep = "$dir/csvdatasave.csv";
      print(filep);
      final _rawData = await rootBundle.loadString(filep);
      _loadlistData = const CsvToListConverter().convert(_rawData);
      print("from csv");
      print(_loadlistData);
      print("loaded from csv file ");
    } else {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
      ].request();
    }
  }

It shows this error…
Exception has occurred. FlutterError (Unable to load asset: /storage/emulated/0/Android/data/com.example.dpark/files/csvdatasave.csv)
but the file exists

Can anyone help to load the generated csv file from the saved location…

>Solution :

The issue with your code is that you are trying to load the file using rootBundle.loadString(), which is used to load files that are included as assets in your app’s package, and not files that are saved to the external storage directory. To load the CSV file from the external storage directory, you can use the File class and read the contents of the file using readAsString method. Here’s how you can modify your _loadedCSV() method:

_loadedCSV() async {
  if (await Permission.storage.request().isGranted) {
    String dir = (await getExternalStorageDirectory())!.path;
    String filep = "$dir/csvdatasave.csv";
    print(filep);

    File file = File(filep);
    String _rawData = await file.readAsString();
    _loadlistData = const CsvToListConverter().convert(_rawData);

    print("from csv");
    print(_loadlistData);
    print("loaded from csv file ");
  } else {
    Map<Permission, PermissionStatus> statuses = await [Permission.storage].request();
  }
}

Leave a Reply Cancel reply