Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain multiple ImageElement load events in Dart

Tags:

dart

I converted a JavaScript background image loader to Dart, kinda like this: Javascript image loader

And I use a Timer to check if the images are all loaded. This works OK.

But in Dart there are chainable Futures and I was wondering if you could chain the background loading of ImageElements...

ImageElement a = new ImageElement();
ImageElement b = new ImageElement();
ImageElement c = new ImageElement();

Future.wait([a.src='a.jpg', b.src='b.jpg', c.src='ca.jpg'])
  .then((List responses) => chooseBestResponse(responses))
  .catchError((e) => handleError(e));

Of course assigning src and the actual image loading is asynchronous so this won't work...

I also need some code to execute for each image once it is loaded.

Maybe I need to write my own FutureImageElement class, but I thought I'd ask first...

Any ideas ?

like image 233
Ray Hulha Avatar asked Apr 15 '13 00:04

Ray Hulha


1 Answers

Sure, you can use futures. Just use the first property of streams:

var a = new ImageElement(src: 'a.png');
var b = new ImageElement(src: 'b.png');
var c = new ImageElement(src: 'c.png');

var futures = [a.onLoad.first, b.onLoad.first, c.onLoad.first];

Future.wait(futures).then((_) => print('done'));

The text "done" will be printed when all three images are loaded.

like image 88
Kai Sellgren Avatar answered Oct 29 '22 09:10

Kai Sellgren