flutter - 如何在 web 中使用 file_picker 显示选取的图像?
问题描述
当文件路径在网络file_picker
平台中时,如何在网络中显示图像?null
如果路径不为空,则显示图像太容易了Image.file(File)
:
Image.file(context.select<BlogProvider, File>((BlogProvider p) => p.image))
但它无法在网络中为图像创建文件,因为浏览器不提供文件路径并且它为空。
Future<void> pickImage() async {
/// If [withReadStream] is set, picked files will have its byte data available as a [Stream<List<int>>]
/// which can be useful for uploading and processing large files.
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg'],
withReadStream: true,
);
if (result != null) {
PlatformFile file = result.files.single; //single means I am Picking just One file not more
_blogImage = File(file.path);//Null in web ,but Ok in Android
notifyListeners();
} else {
// User canceled the picker
}
}
解决方案
当withReadStream设置为true时,可以通过以下方式访问所选图像:
file.readStream.listen((event) {
_blogImage = Image.memory(event);
notifyListeners();
});
但是当withReadStream为false时:
_blogImage = Image.memory(file.bytes);
notifyListeners();
尽管在web的Flutter中file.path为null ,但file.name设置正确,我们可以显示它。
更多信息在这里
另一种方式(没有file_picker包):
import 'dart:html' as html;
// ...
void pickFile() {
final input = html.FileUploadInputElement()..accept = 'image/*';
input.onChange.listen((event) {
if (input.files.isNotEmpty) {
fileName = input.files.first.name; // file name without path!
// synthetic file path can be used with Image.network()
url = html.Url.createObjectUrl(input.files.first);
});
}
});
input.click();
}
推荐阅读
- python - NameError 与第一个 python 脚本
- jenkins - 从詹金斯管道中的脚本运行 liquibase 更新
- java - 是否可以比较 Firestore 中的两个集合?
- node.js - 带有“export * as”语法的 node_modules 包中的打字稿错误
- java - 由于某种原因,当我使用带有 LocalDateTime 变量的 Spring Boot 时,不会创建我的数据库
- php - Laravel 路由存在但无法查看页面
- c++ - 如何将 N 位写入 QByteArray
- reactjs - 将焦点更改为另一个文本框时清除 React 中的文本输入
- java - getter 的返回类型是否与 setter 的参数类型匹配?
- binary-search-tree - 如果在 BST 中获取中序后继需要 O(h),为什么在调用 O(h) 函数 n 次时迭代中序遍历需要 O(n)?