CameraController class
High-level controller that mirrors the vision_camera API surface.
Quick start
// 1. Get devices (like Camera.getAvailableCameraDevices in vision_camera)
final devices = await CameraController.getAvailableCameraDevices();
final back = devices.firstWhere((d) => d.isBackCamera);
// 2. Pick a format (optional — defaults to the best available)
final format = back.formats.first;
// 3. Create and initialise
final controller = CameraController(device: back, format: format);
await controller.initialize();
// 4. Render
CameraPreview(controller: controller)
- Inheritance
-
- Object
- ChangeNotifier
- CameraController
Constructors
- CameraController({required CameraDeviceInfo device, CameraDeviceFormat? format, bool audio = false, bool photo = true, bool directPreview = false, NitroCamera? native})
Properties
- audio → bool
-
Whether to capture audio during video recording.
final
- configuration → CameraConfiguration?
-
The last-applied declarative configuration (null until initialize).
no setter
-
depthFrames
→ Stream<
DepthFrame> -
Depth maps of this session (float32 metres — see
DepthFrame.metres).no setter -
detections
→ Stream<
DetectionResult> -
Typed native-detector results for THIS session (vision-camera-style).
no setter
- device → CameraDeviceInfo
-
The camera device to open.
final
- directPreview → bool
-
Lets the camera write straight into the preview Texture, skipping the
native GL copy (Android, ImageReader-backed textures; ~3 % of a core
at 30 fps). CameraPreview frames it from previewTransform. Only for
PreviewMode.texture — a platform view needs the GL path. The session
falls back to GL by itself when a shader, lens undistortion or GL
recording needs it.
final
- encodedOutputStats → EncodedOutputStats
-
Counters of the running encoder output (zeros when none is running).
no setter
-
events
→ Stream<
CameraSessionEvent> -
Typed session events (started / stopped / error / interruption) for this
session. Mirrors vision-camera's session listeners.
no setter
- exposure → double
-
no setter
- flash → FlashMode
-
no setter
- format → CameraDeviceFormat?
-
The capture format to use. Defaults to the first format in
device.formats.final -
frameDropReasons
→ Stream<
FrameDropReason> -
Typed frame-drop reasons for this session (vision-camera's
onFrameDropped) — a sustained stream of these means the frame processor can't keep up (drop-latest backpressure is discarding frames).no setter -
frameStream
→ Stream<
CameraFrame> -
Stream of raw camera frames for this session (only active after
enableFrameProcessing). Frames from other concurrently-open sessions
(multi-cam, the double-buffered switch window) are filtered out.
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
- hasListeners → bool
-
Whether any listeners are currently registered.
no setterinherited
- height → int
-
The height of the camera resolution.
no setter
- isActive → bool
-
Whether the preview/camera session is active.
no setter
- isInitialized → bool
-
True once initialize has completed successfully.
no setter
- isRecording → bool
-
no setter
- isRecordingPaused → bool
-
no setter
-
nativeDetections
→ Stream<
Map< String, dynamic> > -
Decoded native-detector results for THIS session, as parsed JSON maps
(
{detector, width, height, rotation, results: [...]}).no setter - photo → bool
-
Whether the session carries the still (JPEG) output.
falseleaves it out (vision-camera without a photo output) — one stream less for the ISP when only preview + frames are needed, e.g. scanning; takePhoto, takePhotoWithOptions and takeSnapshot then throw a CaptureException. Android only; iOS/macOS always attach it.final - previewTransform → PreviewTransform
-
How CameraPreview must frame the Texture right now (see
PreviewTransform);
direct == 0means the native side already did.no setter -
resizedFrames
→ Stream<
ResizedFrame> -
GPU-resized tensors of this session (startResizer); read
data(orResizedFrame.float32) inside the listener only.no setter - resolvedConfig → ResolvedCameraConfig?
-
What format negotiation actually selected — the analogue of
vision-camera's
onSessionConfigSelectedread-back.no setter - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- sensorOrientation → int
-
The physical orientation of the camera sensor (90/270 for portrait).
no setter
-
synchronizedFrames
→ Stream<
SyncedFrame> -
Frame + depth pairs of this session (setSynchronizedOutput); read
pixels/SyncedFrame.metresinside the listener only.no setter - textureId → int?
-
The Flutter texture ID. Pass this to
Texture(textureId: controller.textureId!).no setter -
thermalStates
→ Stream<
ThermalState> -
Device thermal-pressure changes while this session is open. Shed capture
load (fps / resolution / HDR) as this climbs toward
ThermalState.critical to avoid a HAL throttle or shutdown. Monitoring
auto-starts with the session (no enable call needed).
no setter
- torch → bool
-
no setter
- width → int
-
The width of the camera resolution.
no setter
- zoom → double
-
no setter
Methods
-
addListener(
VoidCallback listener) → void -
Register a closure to be called when the object changes.
inherited
-
cancelRecording(
) → void - Cancels the recording and deletes the temporary file.
-
closeSession(
) → Future< void> - Closes the native camera session — freeing the camera hardware for the next open — while keeping this controller (and textureId) alive.
-
configure(
CameraConfiguration next) → Future< void> - Applies a new declarative CameraConfiguration, updating only what changed.
-
disableFrameProcessing(
) → void - Disables raw frame delivery.
-
dispose(
) → Future< void> -
Discards any resources used by the object.
override
-
enableFrameProcessing(
) → void - Enables raw frame delivery via frameStream.
-
focus(
double x, double y) → void -
Focus at the normalised coordinates (
x,y) in range 0.0–1.0. Mirrorscamera.focus(point)in vision_camera. -
focusAt(
double x, double y, {FocusAdaptiveness adaptiveness = FocusAdaptiveness.continuous}) → Future< bool> -
Focuses and meters at (
x,y) in 0..1 of the upright preview ((0,0) = top-left) and completes when the focus scan ends:truewhen it ended sharp (iOS reports every completed scan as sharp). With FocusAdaptiveness.locked the lens stays there; with FocusAdaptiveness.continuous continuous AF resumes around the point. Mirrors vision-camera'sfocus(point, { adaptiveness }). -
getSessionState(
) → SessionState - Reads the live native session state (running / resolution / fps / pixel format) as a typed SessionState.
-
initialize(
{int? width, int? height, int? fps, int? frameWidth, int? frameHeight}) → Future< void> - Opens the camera and registers the Flutter texture.
-
lockExposure(
{required bool locked}) → void - Locks / unlocks auto-exposure at its current value.
-
lockFocus(
{required bool locked}) → void - Locks / unlocks focus at its current position.
-
lockWhiteBalance(
{required bool locked}) → void - Locks / unlocks white balance at its current gains.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
notifyListeners(
) → void -
Call all the registered listeners.
inherited
-
pausePreview(
) → void -
pauseRecording(
) → void - Pauses an active recording without finalising the file.
-
releaseNativeBuffer(
CameraFrame frame) → void -
Returns
frame's native buffer to the camera (no-op without one). -
removeListener(
VoidCallback listener) → void -
Remove a previously registered closure from the list of closures that are
notified when the object changes.
inherited
-
resumePreview(
) → void -
resumeRecording(
) → void - Resumes a paused recording.
-
setActive(
bool active) → void - Set isActive programmatically — starts or stops the preview stream.
-
setAutoExposure(
) → void - Restores automatic exposure after setManualExposure.
-
setAutoFocus(
AutoFocusMode mode) → void - Sets the auto-focus mode.
-
setDepthOutput(
{required bool enabled}) → Future< void> -
Turns the depth stream (depthFrames) on or off — vision-camera's
CameraDepthFrameOutput. Needs a camera whose format reports
supportsDepthCapture(iOS TrueDepth / dual / LiDAR, Android DEPTH_OUTPUT); otherwise throwsDeviceException('device/depth-unsupported'). Android reconfigures the session (a brief preview blink), so it refuses during a recording withSessionException('session/busy'). -
setDistortionCorrection(
{required bool enabled}) → void -
Enables / disables lens distortion correction (default ON where the
device supports it — API 28+). vision-camera's
enableDistortionCorrection. -
setExposure(
double value) → void -
Exposure bias in the range
device.minExposure..device.maxExposure. -
setExtension(
CameraExtension? extension) → Future< void> -
Turns a vendor camera extension on (Android 12+ night, HDR, bokeh, face
retouch or auto — see CameraDeviceInfo.extensions) or off (
null). While one is on, the session carries only the preview and stills: frame processing, depth and recording are unavailable, and stills take the extension's processing time. ThrowsDeviceException('device/extension-unsupported')when unavailable (always on iOS),SessionException('session/busy')while recording. -
setFilterShader(
String glslSource) → void - Updates the GPU filter shader applied to the preview.
-
setFlash(
FlashMode mode) → void - Flash mode for photo capture.
-
setFocusDistance(
double distance) → void -
Manually fixes the focus distance:
distance0.0 (far / infinity) to 1.0 (nearest). Pass a negative value to restore continuous auto-focus. Fixed-focus lenses (and iOS devices without custom-lens-position support) ignore it. See CameraDeviceInfo.minFocusDistanceCm for the near limit. -
setFrameProcessing(
{required bool enabled}) → void - Enables or disables raw frame delivery via frameStream.
-
setHdr(
{required bool enabled}) → void - Enables or disables HDR mode.
-
setLowLightBoost(
{required bool enabled}) → void - Enables or disables low-light boost (night mode).
-
setManualExposure(
{required double iso, required Duration exposureDuration}) → void -
Manual exposure: fixes ISO (
iso, e.g. 100-3200) and shutter time (exposureDuration). Both are clamped to the device's range. Pass a non-positiveisoto restore automatic exposure. -
setNativeBuffers(
{required bool enabled}) → void -
Attaches the camera's own buffer to frames —
CameraFrame.nativeBuffer/FrameData.nativeBuffer, anAHardwareBuffer*(Android 9+) or aCVPixelBufferRef(iOS) — vision-camera'sframe.getNativeBuffer(), for GPU / ML code that imports it without a copy. One buffer is held at a time; a CameraFrameProcessor returns it after each handler, raw frameStream listeners call releaseNativeBuffer. A buffer is valid until released or 1 s after delivery, whichever comes first — the camera reclaims unreleased ones, so don't use it past that. ThrowsDeviceException('device/native-buffer-unsupported')below Android 9. -
setNativeDetector(
String detector) → void -
Runs a NATIVE detector on this session's frames by registered name —
"barcode"/"face"(built-ins),""to stop, or the name of a custom detector the host app registered viaNitraDetectors.register(...)(Kotlin/Swift). Results arrive on detections / nativeDetections. -
setOverlay(
CameraOverlay? overlay) → void -
Draws
overlayinto the camera output — the preview AND recordings show it, burned in — until replaced;nullor an empty overlay clears it. The role vision-camera's Skia frame processors play for bounding boxes, labels and guides. Frame processors, the resizer and photos get the frame without it. On Android it moves a direct preview to the GL renderer. -
setPixelFormat(
PixelFormat format) → void - Frame-stream pixel format.
-
setSamplingRate(
int rate) → void - Deliver every Nth frame to frameStream (1 = every frame).
-
setSynchronizedOutput(
{required bool enabled}) → Future< void> -
Pairs each video frame with the depth map captured WITH it and streams
the pairs on synchronizedFrames — vision-camera's
CameraOutputSynchronizer. Turns depth output on as needed, so it throws
the same
device/depth-unsupported/session/busyerrors as setDepthOutput. The plain frameStream and depthFrames keep working alongside. -
setTargetOrientation(
int degrees) → void - Sets the target output orientation in degrees (0 / 90 / 180 / 270).
-
setTorch(
{required bool enabled}) → void - Continuous torch (flashlight) on/off.
-
setTorchLevel(
double level) → void - Torch brightness in 0.0..1.0 (1.0 = max). Values > 0 imply torch on.
-
setVideoStabilization(
VideoStabilizationMode mode) → void - Video stabilization mode.
-
setWhiteBalance(
int kelvin) → void - White balance colour temperature in Kelvin. Pass 0 to restore auto.
-
setZoom(
double zoom) → void -
Zoom factor clamped to
device.minZoom..device.maxZoom. -
startDetector(
NativeDetector detector) → void - Starts a NATIVE ML Kit detector (NativeDetector.barcode / NativeDetector.face) on this session's frames. Results arrive typed on detections. Requires the host app to add the matching ML Kit dependency (documented in the README).
-
startEncodedOutput(
{int width = 720, int height = 1280, int bitRate = 2500000}) → void -
Attaches a hardware H.264 encoder to the session through the native
NitroCameraOutputshook (the path an RTMP / WebRTC publisher plugin takes); replaces a running one.width/heightapply on Android; iOS encodes at the session's frame size. -
startHighSpeedRecording(
String outputPath, {int fps = 240}) → Future< bool> -
Starts a slow-motion recording to
outputPathatfps(typically 120 or 240). Uses a dedicated high-speed capture session; photo capture and frame processing are unavailable until stopHighSpeedRecording is called. -
startRecording(
String outputPath, {VideoCodec codec = VideoCodec.h264, VideoFileType fileType = VideoFileType.mp4, int? bitRate, Duration? maxDuration, int? maxFileSize, ({double altitude, double latitude, double longitude})? location, bool persistent = false, RecordingOptions? options}) → Future< void> -
Starts recording to
outputPath. -
startResizer(
{required int width, required int height, TensorLayout layout = TensorLayout.rgb, TensorDataType dataType = TensorDataType.uint8, ResizeFit fit = ResizeFit.cover}) → Future< void> -
Starts (or reconfigures) the GPU resizer: every frame is scaled on the
GPU into a
width×heightML tensor on resizedFrames — vision-camera-resizer. Upright and un-mirrored. Throws ArgumentError for a non-positive size. -
stopDetector(
) → void - Stops the native detector.
-
stopEncodedOutput(
) → void - Detaches the encoder output. No-op when none is running.
-
stopHighSpeedRecording(
) → Future< RecordingResult> - Stops a slow-motion recording started with startHighSpeedRecording and restores the normal preview session. Returns the file path and metadata.
-
stopRecording(
) → Future< RecordingResult> - Stops and finalises the recording. Returns the file path and metadata.
-
stopResizer(
) → Future< void> - Stops the GPU resizer.
-
takePhoto(
) → Future< PhotoResult> - Captures a photo. Returns the file path and metadata.
-
takePhotoWithOptions(
PhotoCaptureOptions options) → Future< PhotoResult> -
Captures a photo with explicit
options(flash, quality, shutter sound…). -
takeSnapshot(
) → Future< PhotoResult> - Captures the current preview frame as a fast JPEG snapshot (no full still-capture round-trip).
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Properties
-
allEvents
→ Stream<
CameraSessionEvent> -
Typed session events across all open sessions.
no setter
Static Methods
-
allEventsOf(
NitroCamera native) → Stream< CameraSessionEvent> - Typed session events from an explicit bridge — the injectable form of allEvents, used by thermalStates and by tests.
-
getAvailableCameraDevices(
{NitroCamera? native}) → Future< List< CameraDeviceInfo> > - Returns all available camera devices, each with their supported formats.
-
getConcurrentCameraIds(
{NitroCamera? native}) → List< List< String> > - Camera-ID combinations that can stream CONCURRENTLY (multi-cam, API 30+). Each inner list is one combination that initialize can open as simultaneous CameraController instances. Empty when unsupported.
-
getConcurrentCameraSets(
{NitroCamera? native}) → Future< List< ConcurrentCameraSet> > - Convenience: the platform's concurrent-camera combinations as typed ConcurrentCameraSets (combines getConcurrentCameraIds with getAvailableCameraDevices). Empty when multi-cam is unsupported.
-
pickConcurrentSet(
List< ConcurrentCameraSet> sets, {required CameraPosition a, CameraPosition? b}) → ConcurrentCameraSet? -
The first ConcurrentCameraSet that contains a device facing
aand (when given)b— e.g.pickConcurrentSet(sets, a: back, b: front)for a main-plus-selfie layout. Returns null when no combination qualifies. -
requestCameraPermission(
{NitroCamera? native}) → Future< PermissionStatus> - Shorthand: request camera permission and return the status.
-
requestMicrophonePermission(
{NitroCamera? native}) → Future< PermissionStatus> - Shorthand: request microphone permission and return the status.
-
resolveConcurrentSets(
List< List< idCombos, List<String> >CameraDeviceInfo> devices) → List<ConcurrentCameraSet> -
Turns the raw concurrent-camera ID combinations into typed
ConcurrentCameraSets using the enumerated
devices. A combo is dropped if any of its IDs is not present indevices(a stale/foreign id). Pure — no native calls, so it is unit-testable off-device. -
setMultiCam(
{required bool enabled, NitroCamera? native}) → void -
Runs the cameras opened from now on SIMULTANEOUSLY — vision-camera's
requiresMultiCam. On iOS they then share one AVCaptureMultiCamSession (without it iOS runs one camera at a time and a second open interrupts the first); pick pairs from getConcurrentCameraIds. Opening a camera that can't join (unsupported pair, or the cameras together exceed the hardware budget) fails like any other open — initialize throws. Depth and hardware detectors are unavailable in multi-cam mode on iOS. Android runs concurrent cameras natively, so this is a no-op there.