salim-lachdhaf / dartFTP

dartFTP
MIT License
9 stars 17 forks source link

Error while downloading file #23

Open aditya-wappnet opened 1 year ago

aditya-wappnet commented 1 year ago

i get this error when i try to download file in my device redmi note 9 pro but the same code for downloading file is working for other device realme error is - RangeError (index): Invalid value: Only valid value is 0: -1

logic -- Future downloadFile() async { await initializeFTP(); showCustomLoadingDialog();

isDownloading = true;
downloadProgress = 0.0;

print("Downloading files...");
List<Map<String, dynamic>> allDeliveryLogs = [];

try {
  print("Connecting to FTP server...");

  // Assuming you have an initialized FTP client stored in the variable ftpConnect
  // ...

  print("Changing directory...");
  await ftpConnect!
      .changeDirectory('/ftp/DeliverEsignService/1472589/A/Import/');

  print("Retrieving directory content...");
  final directoryContent = await ftpConnect!.listDirectoryContent();
  print("FTP Server Response: $directoryContent");

  print("Filtering file names...");
  final fileNames = directoryContent
      .where((entry) => entry.name.toLowerCase().endsWith('.db'))
      .map((entry) => entry.name)
      .toList();

  print('File names found: $fileNames');
  if (fileNames.isEmpty) {
    print('No files found for download.');
  }

  // Download and store each file locally
  for (int i = 0; i < fileNames.length; i++) {
    String fileName = fileNames[i];
    print('Processing file $i: $fileName');

    String serverFilePath =
        '/ftp/DeliverEsignService/1472589/A/Import/$fileName';

    // Get the local app directory path using path_provider
    Directory appDir = await getApplicationDocumentsDirectory();
    String localFilePath = '${appDir.path}/$fileName';
    File localFile = File(localFilePath);

    print('Downloading file: $fileName');

    try {
      await ftpConnect?.downloadFileWithRetry(
        serverFilePath,
        localFile,
        onProgress: (progress, received, total) {
          print('Download progress: $progress ($received / $total)');

          downloadProgress = progress;
        },
      );

      print('File downloaded successfully: $fileName');

      // Open the database
      Database database = await openDatabase(localFilePath);

      // Print the schema of the 'deliveryLog' table
      List<Map<String, dynamic>> columns =
          await database.rawQuery("PRAGMA table_info('deliveryLog')");
      print('Table Schema: $columns');

      // Retrieve the data from the SQLite database
      List<Map<String, dynamic>> deliveryLogsData =
          await database.rawQuery('SELECT * FROM deliveryLog');
      print('deliveryLogs: $deliveryLogsData');

      // Create a List of DeliveryLog objects from the database data
      List<DeliveryLog> deliveryLogs = deliveryLogsData
          .map((data) => DeliveryLog(
                recordId: data['recordId'],
                patientID: data['PatientID'],
                nursingHomeID: data['NurshingHomeID'],
                rxID: data['RxID'],
                driverID: data['DriverID'],
                rxNumber: data['RxNumber'],
                fillDate: data['Fill_Date'],
                patientName: data['Patient_Name'],
                address: data['Address'],
                nursingHomeName: data['Nursing_Home_Name'],
                drug: data['Drug'],
                status: data['Status'],
                recipient: data['Recipient'],
                sign: data['Sign'],
                deliveredDateTime: data['Delivered_Date_Time'],
                amount:
                    data['Amount'], // Convert to double if it's not null
                paymentType: data['PaymentType'],
                paymentAmount: data[
                    'PaymentAmount'], // Convert to double if it's not null
              ))
          .toList();

      // Convert List<DeliveryLog> to List<Map<String, dynamic>>
      List<Map<String, dynamic>> deliveryLogsMapList =
          deliveryLogs.map((log) => log.toMap()).toList();

      // Add the delivery logs to the list
      allDeliveryLogs.addAll(deliveryLogsMapList);

      // Store the deliveryLogs in Hive
      await storeUniqueLogsInHive(deliveryLogs);

      // Close the database connection
      await database.close();
    } catch (e) {
      closeCustomLoadingDialog();
      showCustomSnackBar('Error downloading file: $fileName - $e');
      // Delete the corrupted file
      await localFile.delete();
      print('Corrupted file deleted: $fileName');
    }
  }
} catch (e) {
  closeCustomLoadingDialog();
  showCustomSnackBar("Error: $e");
  print(e);
} finally {
  closeCustomLoadingDialog();
  print("Disconnecting from FTP server...");
  await ftpConnect?.disconnect();

  isDownloading = false;
  downloadProgress = 0.0;
}

// Print the retrieved data print('All Delivery Logs: $allDeliveryLogs'); closeCustomLoadingDialog(); } i have also tried to give static path for single file to download then also i get error i would love if some one say what the issue

salim-lachdhaf commented 7 months ago

have you a simple to reproduce the issue ?