asynchronous - How do I properly download and save a list of images? -
i have list of image of urls , download , save each image. unfortunately, keep receiving out of memory exception due exhausted heap space. last attempt saved 2 images , threw "exhausted heap space, trying allocate 33554464 bytes".
my code shown below. logic seems correct believe asynchronous calls may @ fault. there adjustment should make cause downloading sequential? or there method should utilizing?
import 'package:http/http.dart' http; import 'dart:io'; main() { // loc set of valid urls // ... loc.foreach(retrieveimage) } void retrieveimage(string location) { uri uri = uri.parse(location); string name = uri.pathsegments.last; print("reading $location"); http.readbytes(location).then((image) => saveimage(name, image)); } void saveimage(string name, var data) { new file("${name}") ..writeasbytessync(data); print(name); }
if want download them sequentially, can switch future.foreach
. enumerators through collection executing function each, waiting future function returns complete before moving on next. it, in turn, returns future completes once final iteration has completed.
instead of
loc.foreach(retrieveimage);
use
future.foreach(loc, retrieveimage);
and ensure retrieveimage
returns future:
future retrieveimage(string location) { uri uri = uri.parse(location); string name = uri.pathsegments.last; print("reading $location"); return http.readbytes(location).then((image) => saveimage(name, image)); }
Comments
Post a Comment