如何在Flutter中将图像从URL获取到文件? [英] How to get Image from URL to a File in Flutter?

查看:793
本文介绍了如何在Flutter中将图像从URL获取到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存在Firebase Storage上的图像.如何将图像文件的URL分配给文件?

I have an image saved on Firebase Storage. How can I assign this URL of the image file to a File?

有什么方法可以做到的吗?

Is there some way to do it as:

File file = File(URL);

我也尝试过使用http,但是会导致错误:抛出FileSystemException以解决图像编解码器:无法打开文件"

I've also tried using http, but results in an error : 'FileSystemException was thrown resolving an image codec: Cannot open file'

final http.Response responseData = await http.get(url);
Uint8List uint8list = responseData.bodyBytes;
File file = File.fromRawPath(uint8list);

使用Uint8list具有有效数据,如使用下面所示的小部件时所见, 但与上面的代码File.fromRawPath(unint8list)一起使用时出现错误

Using Uint8list has valid data, as seen when using widget shown below, but gives an error when used with above code, File.fromRawPath(unint8list)

Image.memory(uint8list);

尝试使用ImageProvider,但无法从中获取File对象:

Tried using ImageProvider but can't get a File object from it:

ImageProvider imageProvider = NetworkImage(url);

推荐答案

设法获取File对象,不得不以其他方式使用Uint8List,因此现在将使用它,这是工作代码:

Managed to get the File object, had to use Uint8List in a different way, so will use it for now, here is the working code:

final http.Response responseData = await http.get(strURL);
uint8list = responseData.bodyBytes;
var buffer = uint8list.buffer;
ByteData byteData = ByteData.view(buffer);
var tempDir = await getTemporaryDirectory();
File file = await File('${tempDir.path}/img').writeAsBytes(
    buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

这篇关于如何在Flutter中将图像从URL获取到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆