takePicture method

Future<MediaEntity?> takePicture()

Implementation

Future<MediaEntity?> takePicture() async {
  if (!initialized) {
    _uiHandler.showSnackBar('Couldn\'t find the camera!');
    return null;
  }

  if (value.isTakingPicture) {
    _uiHandler.showSnackBar('Capturing is currently running..');
    return null;
  }

  try {
    value = value.copyWith(isTakingPicture: true);

    final xFile = await controller.takePicture();
    final file = File(xFile.path);
    final data = await file.readAsBytes();
    final entity = await PhotoManager.editor.saveImage(
      data,
      title: path.basename(file.path),
    );

    if (file.existsSync()) {
      file.deleteSync();
    }

    value = value.copyWith(isTakingPicture: false);

    if (entity != null) {
      final mediaEntity = MediaEntity(entity: entity, bytes: data);
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
          overlays: SystemUiOverlay.values);
      _uiHandler.pop<MediaEntity>(mediaEntity);
      return mediaEntity;
    } else {
      _uiHandler.showSnackBar('Something went wrong! Please try again');
      value = value.copyWith(isTakingPicture: false);
      return null;
    }
  } on CameraException catch (e) {
    _uiHandler
        .showSnackBar('Exception occurred while capturing picture : $e');
    value = value.copyWith(isTakingPicture: false);
    return null;
  } catch (e) {
    _uiHandler
        .showSnackBar('Exception occurred while capturing picture : $e');
    return null;
  }
}