How to cast/convert Future into Image?

2019-07-24 17:25发布

问题:

I have function to fetch image like

dynamic imgBinary = _repository.fetchImage(productId);

And I want to add this into List of Image

List<NetworkImage> listImages = new List<NetworkImage>();

So like

dynamic imgBinary = _repository.fetchImage(productId);
listImages.add(imgBinary);

How to cast this?

回答1:

Ok , So you Can Try .then method.

As _repository.fetchImage(productId); is Future.

so you can try -

List<NetworkImage> listImages = List<NetworkImage>();
    Future<dynamic> imgBinary = _repository.fetchImage(productId);
    imgBinary.then((i){
    listImages.add(i);
    });

or

Directly:

_repository.fetchImage(productId).then((i){
listImages.add(i);});

To get the Value from Future - we can either use :

async and await

OR you can use the then() method to register a callback. This callback fires when the Future completes.

For more info



回答2:

EDIT: anmol.majhail's answer is better

Your fetchImage method needs to return a future, here's some pseudo code as guidence

List<NetworkImage> listImages = new List<NetworkImage>();

Future<void> _fetchAddImageToList(int productId) async {
     //trycatch
    dynamic imgBinary = await _repository.fetchImage(productId);
    listImages.add(imgBinary);
}

Future<NetworkImage> fetchImage(int id) async {
    New NetworkImage img = new NetworkImage();
    //do your fetch work here
    return img;
}