switchToDesiredStateProtected method

Future<void> switchToDesiredStateProtected(
  1. FrameSourceState state,
  2. CameraOwner owner
)

Switches the camera to the desired state with ownership protection.

This method ensures that only the current owner of the camera can change its state. If the provided owner is not the current owner, the state change will be ignored to prevent conflicts between multiple components trying to control the same camera.

RECOMMENDED: Use CameraOwnershipHelper for easier ownership management:

final owner = MyFeatureOwner(); // implements CameraOwner

// Option 1: Use helper to acquire ownership and perform operation
await CameraOwnershipHelper.withCamera<void>(
  CameraPosition.worldFacing,
  owner,
  (camera) async => await camera.switchToDesiredStateProtected(FrameSourceState.on, owner)
);

// Option 2: Request ownership first, then use camera
final success = await CameraOwnershipHelper.requestOwnership(CameraPosition.worldFacing, owner);
if (success) {
  final camera = CameraOwnershipHelper.getCamera(CameraPosition.worldFacing, owner);
  await camera?.switchToDesiredStateProtected(FrameSourceState.on, owner);
}

Manual ownership management (not recommended):

final camera = Camera.defaultCamera;
final owner = MyFeatureOwner();

// Manual approach - use CameraOwnershipHelper instead
CameraOwnershipManager.getInstance().requestOwnership(camera.position, owner);
await camera.switchToDesiredStateProtected(FrameSourceState.on, owner);

EXPERIMENTAL: This API is experimental and may change or be removed in future versions without prior notice.

Parameters:

  • state: The desired frame source state to switch to
  • owner: The camera owner requesting the state change

Implementation

Future<void> switchToDesiredStateProtected(FrameSourceState state, CameraOwner owner) async {
  final ownershipManager = CameraOwnershipManager.getInstance();
  final currentOwner = ownershipManager.getCurrentOwner(position);

  if (currentOwner == null) {
    throw Exception('Camera operation denied: No owner for camera at $position');
  }

  if (currentOwner.id != owner.id) {
    throw Exception('Camera operation denied: ${owner.id} does not own camera at $position');
  }

  return switchToDesiredState(state);
}