import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'dart:io';
Future<String> saveImageFileToFirestore({required String url}) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/image.jpg');
await file.writeAsBytes(bytes);
File compressedFile = await compressAndGetFile(file, '${directory.path}/image2.jpg');
String imageName = generateImageName();
String downloadUrl = await storeFileImageToStorage('${Constants.images}/$imageName', compressedFile);
return downloadUrl;
}
Future<String> storeFileImageToStorage(String ref, File file) async {
UploadTask uploadTask = firebaseStorage.ref().child(ref).putFile(file);
TaskSnapshot taskSnapshot = await uploadTask;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
return downloadUrl;
}
Future<File> compressAndGetFile(File file, String targetPath) async {
var result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path, targetPath,
quality: 88,
);
return result!;
}
我正在尝试压缩下载的图像并将文件保存到 Firestore DB。当我运行代码时,它会抛出此错误消息。无法从“compressAndGetFile”方法返回“XFile”类型的值,因为它的返回类型为“Future”。它不会接受:
返回结果!;
如果有人可以提供帮助,我将不胜感激。我希望代码运行时不会出现错误。
FlutterImageCompress.compressAndGetFile
返回 Future<XFile?>
并且它所包装的函数返回 Future<File>
。尝试将其转换为 File
中的解决方案,如下所示:return File(result!.path);