Flutter: Trying to compress image and save the file to Cloud Storage through Firebase

83 views Asked by At
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!;
  }

I'm trying to compress a downloaded image and save the file to Firestore DB. When I run the code, it throws this error message. A value of type 'XFile' can't be returned from the method 'compressAndGetFile' because it has a return type of 'Future'. It won't accept:

return result!;

I would appreciate if someone can help. I am expecting the code to run without the error.

1

There are 1 answers

0
Cabdirashiid On BEST ANSWER

FlutterImageCompress.compressAndGetFile returns a Future<XFile?> and the function it's wrapped it returns Future<File>. Try the solution in this answer by converting it to File like so:

return File(result!.path);