在image_cropper flutter中处理来自image_picker的空文件



我正在尝试使用image_picker包获取图像,然后传递给image_cropper。我采取了一种有点不同的方法来避免在选择图像后回到主屏幕,然后再裁剪图像屏幕。

这是我的图像选择和图像裁剪代码。

Future<File> getImageFromGallery(BuildContext context) async{
final File croppedImage = await ImageCropper.cropImage(
sourcePath: File((await ImagePicker().getImage(source: ImageSource.gallery)).path).path,
maxWidth: 1080,
maxHeight: 1080,
aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
);
if (croppedImage  != null) {
return croppedImage;
}
return null;
}
Error: The getter 'path' was called on null.

在尝试的Null Safety中,但随后它抛出以下错误:

Failed assertion: line 81 pos 12: 'await File(sourcePath).exists()': is not true.

我的代码为空安全。

Future<File> getImageFromGallery(BuildContext context) async{
final File croppedImage = await ImageCropper.cropImage(
sourcePath: File((await ImagePicker().getImage(source: ImageSource.gallery)).path).path,
maxWidth: 1080,
maxHeight: 1080,
aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
);
if (croppedImage  != null) {
return croppedImage;
}
return null;
}

请给我一个更好的方法来做我想做的事。

var img = await ImagePicker().getImage(source: ImageSource.gallery);
final File croppedImage = await ImageCropper.cropImage(
sourcePath: img.path,
maxWidth: 1080,
maxHeight: 1080,
aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
);

我认为你应该先拿起img,检查它是否有效。然后将路径传递给imageCropper。所以上面的代码应该可以正常工作。。

最新更新