pickImage method

Future<File?> pickImage({
  1. required BuildContext context,
  2. required ImageFrom source,
})

Implementation

Future<File?> pickImage({required BuildContext context, required ImageFrom source}) async {
  cameraUiSettings?.initialCameraSide ??= CameraSide.back;

  try {
    if (source == ImageFrom.camera) {
      debugPrint("This is camera settings: ${cameraUiSettings?.toJson()}");

      file = await Navigator.push(
        context,
        CupertinoPageRoute(
          builder: (context) => CameraPlugin(cameraUiSettings: cameraUiSettings),
        ),
      );
    } else {
      final imagePicker = ImagePicker();
      final pickedFile = await imagePicker.pickImage(source: ImageSource.gallery);

      if (pickedFile != null) {
        debugPrint('Image picked successfully: ${pickedFile.path}');
        file = File(pickedFile.path);
      } else {
        debugPrint('User canceled image picking');
      }
    }

    if (compressImage && file != null) {
      if (!compressOnlyForCamera || (compressOnlyForCamera && source == ImageFrom.camera)) {
        final sizeInKbBeforeCompression = file!.lengthSync() / 1024;
        debugPrint('Before Compress: $sizeInKbBeforeCompression KB');

        file = await compress(image: file!, compressParams: compressParams ?? defaultCompress);

        final sizeInKbAfterCompression = file!.lengthSync() / 1024;
        debugPrint('After Compress: $sizeInKbAfterCompression KB');
      }
    }

    return file;
  } catch (e) {
    debugPrint('Error picking image: ${e.toString()}');
    return null;
  }
}