【问题标题】:Unhandled Exception: type 'List<Set<Future<File>>>' is not a subtype of type 'List<File>' in type cast未处理的异常:类型转换中的类型“List<Set<Future<File>>>”不是类型“List<File>”的子类型
【发布时间】:2021-07-26 09:29:41
【问题描述】:

我会在上传之前压缩一个图像文件列表,但是在使用map一个文件列表后我对转换类型有一些疑问,它返回类型List>,而不是我期望的类型List。在这种情况下,如何转换/转换为文件列表,compressImage 函数仅适用于一个文件。非常感谢。

import 'package:image/image.dart' as Im;  
import 'package:uuid/uuid.dart';  
List<File> compressImageList(List<File> tempfileList) async {
    
    List<Future<File>> compressedFileList =
        tempfileList.map((file) => {compressImage(file)}).toList();

    return compressedFileList ;
  }

  Future<File> compressImage(File tempFile) async {
  String postId = Uuid().v4();
    final tempDir = await getTemporaryDirectory();
    final path = tempDir.path;
    Im.Image? imageFile = Im.decodeImage(tempFile.readAsBytesSync());
    final compressedImageFile =  File('$path/img_$postId.jpg')
      ..writeAsBytesSync(Im.encodeJpg(imageFile!, quality: 85));

    tempFile = compressedImageFile;
    return tempFile;
  }

我编辑我的功能如下,它可以工作,谢谢。

 Future<List<File>> compressImageList(List<File> tempfileList) async {
List<File> compressedFileList = [];
await Future.wait(tempfileList.map((file) async {
  var compressImage2 = await compressImage(file);

  compressedFileList.add(compressImage2);
}).toList());
return compressedFileList;

}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    不确定,没有测试过,但是尝试删除第 6 行的 {}(如上所示)。这些括号表示它是一个类型集,由=&gt; 返回。如果对单个语句使用=&gt;,则不需要使用括号。

    【讨论】:

    • 是的,这些括号使 dart add 设置为返回值。谢谢。
    【解决方案2】:

    这样做;

    List<File> compressImageList(List<File> tempfileList) {
      List<File> compressedFiles = [];
      tempfileList.forEach((file) async {
        final compressedFile = await compressImage(file);
        compressedFiles = [...compressedFiles, compressedFile];
      });
    
      return compressedFiles;
    }
    

    【讨论】:

    • 谢谢,但看来你需要添加 Future.wait()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2021-12-08
    • 1970-01-01
    • 2021-11-28
    • 2019-08-03
    • 2021-09-16
    相关资源
    最近更新 更多