createAssetEntityAndPop method

Future<void> createAssetEntityAndPop()

When users confirm to use the taken file, create the AssetEntity. While the entity might returned null, there's no side effects if popping null because the parent picker will ignore it.

Implementation

Future<void> createAssetEntityAndPop() async {
  if (isSavingEntity) {
    return;
  }
  setState(() {
    isSavingEntity = true;
  });
  final CameraPickerViewType viewType = widget.viewType;
  if (widget.pickerConfig.onEntitySaving != null) {
    try {
      await widget.pickerConfig.onEntitySaving!(
        context,
        widget.viewType,
        File(widget.previewXFile.path),
      );
    } catch (e, s) {
      handleErrorWithHandler(e, widget.pickerConfig.onError, s: s);
    }
    isSavingEntity = false;
    if (mounted) {
      setState(() {});
    }
    return;
  }
  AssetEntity? entity;
  try {
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    if (ps == PermissionState.authorized || ps == PermissionState.limited) {
      switch (viewType) {
        case CameraPickerViewType.image:
          final String filePath = previewFile.path;
          entity = await PhotoManager.editor.saveImageWithPath(
            filePath,
            title: path.basename(previewFile.path),
          );
          break;
        case CameraPickerViewType.video:
          entity = await PhotoManager.editor.saveVideo(
            previewFile,
            title: path.basename(previewFile.path),
          );
          break;
      }
      if (widget.pickerConfig.shouldDeletePreviewFile &&
          previewFile.existsSync()) {
        previewFile.delete();
      }
      return;
    }
    handleErrorWithHandler(
      StateError(
        'Permission is not fully granted to save the captured file.',
      ),
      widget.pickerConfig.onError,
    );
  } catch (e, s) {
    realDebugPrint('Saving entity failed: $e');
    handleErrorWithHandler(e, widget.pickerConfig.onError, s: s);
  } finally {
    isSavingEntity = false;
    if (mounted) {
      Navigator.of(context).pop(entity);
    }
  }
}