urlToFile method

Future<File> urlToFile({
  1. String format = 'png',
})
File file = await '<image-url>'.urlToFile();

Implementation

Future<File> urlToFile({String format = 'png'}) async {
  // get temporary directory of device.
  Directory tempDir = await getTemporaryDirectory();

  // get temporary path from temporary directory.
  String tempPath = tempDir.path;

  // create a new file in temporary path with random file name.
  File file =
      File('$tempPath${DateTime.now().millisecondsSinceEpoch}.$format');

  // call http.get method and pass imageUrl into it to get response.
  http.Response response = await http.get(Uri.parse(this));

  // write bodyBytes received in response to file.
  await file.writeAsBytes(response.bodyBytes);

  // now return the file which is created with random name in
  // temporary directory and image bytes from response is written to // that file.
  return file;
}