gpt4 book ai didi

flutter - 如何监听 ("close"事件)到 flutter web 中的文件下载窗口?

转载 作者:行者123 更新时间:2023-12-04 13:33:52 26 4
gpt4 key购买 nike

我的代码允许使用 universal_html.InputElement uploadInput = universal_html.FileUploadInputElement(); 打开文件上传窗口网页 flutter 并选择必要的文件将它们加载到项目中。如果用户没有选择任何照片并点击关闭/取消窗口,我想对此使用react。 我如何理解用户关闭窗口?



final completer = Completer<List<String>>();
universal_html.InputElement uploadInput = universal_html.FileUploadInputElement();
uploadInput.multiple = true;
uploadInput.accept = 'image/*';
uploadInput.click();

uploadInput.addEventListener('change', (e) async {
final files = uploadInput.files;
Iterable<Future<String>> resultsFutures = files.map((file) {
final reader = universal_html.FileReader();
reader.readAsDataUrl(file);
reader.onError.listen((error) => completer.completeError(error));
return reader.onLoad.first.then((_) => reader.result as String);
});
final results = await Future.wait(resultsFutures);
completer.complete(results);
});

universal_html.document.body.append(uploadInput);
final List<String> images = await completer.future;

uploadInput.remove();


enter image description here

最佳答案

file_picker 的Web 实现中使用了一种管理此类事件的方法。 .
这是一个可以帮助您的代码示例(您还可以从包 here 中找到完整的实现):

import 'dart:html' as html;
import 'dart:async';

Future<html.File?> pickFile(String type) async {
final completer = Completer<List<html.File>?>();
final input = html.FileUploadInputElement() as html.InputElement;
input.accept = '$type/*';

var changeEventTriggered = false;
void changeEventListener(html.Event e) {
if (changeEventTriggered) return;
changeEventTriggered = true;

final files = input.files!;
final resultFuture = files.map<Future<html.File>>((file) async {
final reader = html.FileReader();
reader.readAsDataUrl(file);
reader.onError.listen(completer.completeError);
return file;
});
Future.wait(resultFuture).then((results) => completer.complete(results));
}

void cancelledEventListener(html.Event e) {
html.window.removeEventListener('focus', cancelledEventListener);

// This listener is called before the input changed event,
// and the `uploadInput.files` value is still null
// Wait for results from js to dart
Future.delayed(Duration(milliseconds: 500)).then((value) {
if (!changeEventTriggered) {
changeEventTriggered = true;
completer.complete(null);
}
});
}

input.onChange.listen(changeEventListener);
input.addEventListener('change', changeEventListener);

// Listen focus event for cancelled
html.window.addEventListener('focus', cancelledEventListener);

input.click();

final results = await completer.future;
if (results == null || results.isEmpty) return null;
return results.first;
}
这个想法是依赖于 focus 上的监听器。事件,因此当您在没有加载任何数据的情况下失去对文件选择器窗口的关注时,它将通过 null 完成您的 future 。值(value)。

关于flutter - 如何监听 ("close"事件)到 flutter web 中的文件下载窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63361478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com