pickImageFile function

Future<XFile?> pickImageFile(
  1. BuildContext context, {
  2. UserPictureSource? forcedSource,
})

Safely picks an image file from gallery or camera, regarding access denied.

Implementation

Future<XFile?> pickImageFile(
  BuildContext context, {
  UserPictureSource? forcedSource,
}) async {
  /// Picks an image file from gallery or camera.
  Future<XFile?> innerPickImageFile(
    BuildContext context, {
    bool ignorePlatformException = false,
  }) async {
    final UserPictureSource? source;
    if (forcedSource != null) {
      source = forcedSource;
    } else {
      source = await _getUserPictureSource(context);
      if (source == null) {
        return null;
      }
    }
    final ImagePicker picker = ImagePicker();
    if (source == UserPictureSource.GALLERY) {
      try {
        return await picker.pickImage(
          imageQuality: ImagePickerConstants.imagePickerQuality,
          maxHeight: ImagePickerConstants.imagePickerMaxSize,
          maxWidth: ImagePickerConstants.imagePickerMaxSize,
          source: ImageSource.gallery,
        );
      } on PlatformException catch (e) {
        // On debug builds this catch won't work.
        // Please run on profile/release modes to test it
        if (ignorePlatformException) {
          return null;
        } else if (e.code == 'photo_access_denied') {
          throw PhotoAccessDenied();
        } else {
          rethrow;
        }
      }
    }
    return picker.pickImage(
      imageQuality: ImagePickerConstants.imagePickerQuality,
      maxHeight: ImagePickerConstants.imagePickerMaxSize,
      maxWidth: ImagePickerConstants.imagePickerMaxSize,
      source: ImageSource.camera,
    );
  }

  try {
    return await innerPickImageFile(context);
  } on PhotoAccessDenied catch (_) {
    if (!context.mounted) {
      return null;
    }
    final bool? res = await _onGalleryAccessDenied(context);
    if (res != true) {
      return null;
    }
    // Let's retry
    if (!context.mounted) {
      return null;
    }
    return innerPickImageFile(context, ignorePlatformException: true);
  }
}