downloadImage function

Future<void> downloadImage(
  1. String url,
  2. String filePath
)

Downloads an image from the given url and saves it to the specified filePath. Returns a Future that completes when the image is downloaded and saved successfully. Throws an error if there is any issue with the download process.

Implementation

Future<void> downloadImage(String url, String filePath) async {
  try {
    var response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var file = File(filePath);
      file.createSync(recursive: true);
      await file.writeAsBytes(response.bodyBytes);
      print('Image downloaded and saved to $filePath');
    } else {
      print('Failed to download image: ${response.statusCode}');
    }
  } catch (e) {
    print('Error downloading image: $e');
  }
}