downloadAndExtractZipSkippingRoot function

Future<void> downloadAndExtractZipSkippingRoot(
  1. String url,
  2. String destinationPath
)

Implementation

Future<void> downloadAndExtractZipSkippingRoot(
    String url, String destinationPath) async {
  try {
    // Step 1: Download the ZIP file
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      // Step 2: Save the ZIP file to the local file system
      final file = File('$destinationPath/temp.zip');
      await file.writeAsBytes(response.bodyBytes);

      // Step 3: Extract the ZIP file
      final bytes = file.readAsBytesSync();
      final archive = ZipDecoder().decodeBytes(bytes);

      // Create the destination directory if it does not exist
      final extractDir = Directory(destinationPath);
      if (!extractDir.existsSync()) {
        extractDir.createSync(recursive: true);
      }

      // Determine if there is a root folder
      String? rootFolder;
      for (final file in archive) {
        if (file.isFile) {
          final parts = file.name.split('/');
          if (parts.length > 1) {
            rootFolder = parts[0];
            break;
          }
        }
      }

      // Extract each file in the archive, skipping the root folder
      for (final file in archive) {
        if (file.isFile) {
          final parts = file.name.split('/');
          String filename;
          if (rootFolder != null && parts.length > 1) {
            // Skip the root folder
            filename = '${extractDir.path}/${parts.sublist(1).join('/')}';
          } else {
            // No root folder, use the file name as is
            filename = '${extractDir.path}/${file.name}';
          }
          final data = file.content as List<int>;
          File(filename)
            ..createSync(recursive: true)
            ..writeAsBytesSync(data);
        } else {
          // Handle directories if needed
          final parts = file.name.split('/');
          String directoryName;
          if (rootFolder != null && parts.length > 1) {
            // Skip the root folder
            directoryName = '${extractDir.path}/${parts.sublist(1).join('/')}';
          } else {
            // No root folder, use the directory name as is
            directoryName = '${extractDir.path}/${file.name}';
          }
          Directory(directoryName).createSync(recursive: true);
        }
      }

      print('Download and extraction complete.');
    } else {
      throw Exception('Failed to download file: ${response.statusCode}');
    }
  } catch (e) {
    print('Error: $e');
  }
}