首页 > 解决方案 > 如何将 multi_image_picker2 `Asset` 转换为 `File` 对象?

问题描述

我正在使用包multi_image_picker2来选择多个图像。下面是我的代码。

Future<void> loadAssets() async {
    List<Asset> resultList = <Asset>[];
    String error = 'No Error Detected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 5,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Pick Your Images",
          allViewTitle: "All Photos",
          useDetailsView: false,
          //selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;


    setState(() {
      images = resultList;
      //_error = error;
    });
  }

我需要将这些转换为File对象,以便将它们上传到 Amazon S3。但是我怎样才能把这个Asset对象转换multi_image_picker2成一个File对象呢?

标签: androidiosflutterdartflutter-dependencies

解决方案


你可以简单地使用flutter_absolute_path:

 List<File> allImages = [];

 resultList.forEach((imageAsset) async {
        await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier)
            .then((filePath) {
          File tempFile = File(filePath);
          if (tempFile.existsSync()) {
           allImages.add(tempFile);
          }
        });
      });

推荐阅读