Search code examples
flutterdartuuid

How can I set a unique UUID for my PickedFile?


I'm trying to give an image uploaded from camera a unique id before uploading to Firestore. I've been using Reed Barger's https://www.udemy.com/course/build-a-social-network-with-flutter-and-firebase/ tutorial but some of the code he used has been deprecated. In this case, image compression. His code to compress and set unique image id was

compressImage() async {
    final tempDir = await getTemporaryDirectory();
    final path = tempDir.path;
    Im.Image imageFile = Im.decodeImage(file.readAsBytesSync());
    final compressedImageFile = File('$path/img_$postId.jpg')
      ..writeAsBytesSync(Im.encodeJpg(imageFile, quality: 85));
    setState(() {
      file = compressedImageFile;
    });
  }

The libraries he used include

import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as Im;
import 'package:uuid/uuid.dart';

His variables were

 File file;
 String postId = Uuid().v4();

Since then, the image_picker library allows me to compress the image by seting the imageQuality so there's no need for the image.dart package. How can I modify my code (below) to set a unique image id in the format Reed used?

 PickedFile file;
  String postId = Uuid().v4();

  handleTakePhoto() async {
    Navigator.pop(context);
    file = (await ImagePicker().getImage(
      source: ImageSource.camera,
      maxHeight: 675.0,
      maxWidth: 960,
      imageQuality: 85,
    ));
    final tempDir = await getTemporaryDirectory();
    final path = tempDir.path;
    final compressedImageFile = File('$path/img_$postId.jpg');
    setState(() {
      this.file = file;
      file = compressedImageFile;
    });
  }

As it is, it returns an error that compressedFileImage can't be assigned to type PickedFile. I've tried adding the cast as PickedFile but that doesn't work.


Solution

  • That's because you're creating a File instead of a PickedFile:

    final compressedImageFile = File('$path/img_$postId.jpg');
    

    Just change it to:

    final compressedImageFile = PickedFile('$path/img_$postId.jpg');