How to cast/convert Future<dynamic> into Image?

微笑、不失礼 提交于 2019-12-24 11:25:11

问题


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;
}


来源:https://stackoverflow.com/questions/54627148/how-to-cast-convert-futuredynamic-into-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!