hcSaveNetworkImage method

dynamic hcSaveNetworkImage({
  1. required String name,
  2. required String url,
  3. String customDirectoryName = "Documents",
  4. BuildContext? context,
})

Save Network Image

Implementation

hcSaveNetworkImage(
    {required String name,
    required String url,
    String customDirectoryName = "Documents",
    BuildContext? context}) async {
  Directory appDocDirectory = await getApplicationDocumentsDirectory();
  String path = Platform.isAndroid
      ? hcDirPath
      : "${appDocDirectory.path}/$customDirectoryName";

  try {
    var response = await http.get(Uri.parse(url));
    final bytes = response.bodyBytes;
    bool checkPermission = await Permission.mediaLibrary.isGranted;
    if (checkPermission) {
      File file = File(
          "$path/${DateFormat('yy-HH-mm-ss').format(DateTime.now())}-$name");
      await file.writeAsBytes(bytes);
      ScaffoldMessenger.of(context!).showSnackBar(SnackBar(
        content: Text(
            "File saved successfully to $path/${DateFormat('yy-HH-mm-ss').format(DateTime.now())}-$name"),
      ));
    } else {
      ScaffoldMessenger.of(context!).showSnackBar(const SnackBar(
        content: Text("Storage permission denied !, please try again!"),
      ));
      var status = await Permission.mediaLibrary.status;
      if (!status.isGranted) {
        await Permission.mediaLibrary.request();
      }
    }
  } on FileSystemException catch (e) {
    ScaffoldMessenger.of(context!).showSnackBar(SnackBar(
      content: Text("ERROR: ${e.message} $path/$name"),
    ));
  } catch (e) {
    ScaffoldMessenger.of(context!).showSnackBar(SnackBar(
      content: Text("ERROR: $e"),
    ));
  }
}