toggleTorch method

Future<void> toggleTorch()

Switches the torch on or off.

Does nothing if the device has no torch.

Throws if the controller was not initialized.

Implementation

Future<void> toggleTorch() async {
  final hasTorch = hasTorchState.value;

  if (hasTorch == null) {
    throw const MobileScannerException(
      errorCode: MobileScannerErrorCode.controllerUninitialized,
    );
  } else if (!hasTorch) {
    return;
  }

  torchState.value =
      torchState.value == TorchState.off ? TorchState.on : TorchState.off;

  await _methodChannel.invokeMethod('torch', torchState.value.index);
}