Sub topic 12
Handling pause, resume, and disposal
This chapter assumes you can build a CameraController screen with a live preview, as in the earlier camera chapters. You should also know StatefulWidget lifecycle methods (initState, dispose) and async/await. The chapter covers when to release the camera, how to get it back, and which races to guard against.
Why the camera needs lifecycle handling
A CameraController holds a native camera session: a hardware handle, a texture, and buffers. Only one app can use the camera at a time. If your app keeps the session while it is in the background, three things can go wrong:
- Another app, such as a video call, cannot open the camera.
- The operating system may tear down the session without telling your Dart code. The controller then reports a healthy state while the preview is frozen or black.
- Battery drain and, on some platforms, a visible camera-in-use indicator.
Flutter reports app state changes through WidgetsBindingObserver.didChangeAppLifecycleState. The camera plugin does not release the camera for you, so your code has to.
The lifecycle states that matter
| State | Typical cause | What to do with the camera |
|---|---|---|
| `resumed` | App is visible and focused | Create and initialize a controller if you don't have one |
| `inactive` | App loses focus but may still be visible: permission dialog, incoming call, iOS control center, app switcher | Release the controller |
| `hidden` | App is no longer visible (Flutter 3.13 and later) | Already released at `inactive` |
| `paused` | App is in the background | Already released at `inactive` |
| `detached` | Engine is running with no view | Already released at `inactive` |
Going to the background passes through inactive first. Releasing the camera at inactive is therefore enough, and you can ignore the other transitions.
Problems a naive version runs into
Releasing at inactive and re-initializing at resumed looks simple, but a few cases break it:
- Stale preview. After
dispose(), the controller object still exists. Ifbuildkeeps passing it toCameraPreview, the screen throws. Set your reference tonulland rebuild, so the UI shows a placeholder. initialize()is asynchronous. The app can go inactive, or the screen can be popped, whileinitialize()is still awaiting. When it completes, you would callsetStateon an unmounted widget or leave an orphaned controller holding the camera.- Rapid transitions.
inactive, thenresumed, theninactivecan arrive in quick succession. Twoinitialize()calls can overlap. - The permission dialog. On first launch,
initialize()triggers the system permission prompt. The prompt pushes the app toinactive. Your handler releases the controller whileinitialize()is still pending. When the user answers and the app resumes, you need a fresh controller. - Disposing twice. Releasing at
inactiveand then again indispose()is easy to do by accident. Clearing the field after disposal avoids it.
The fix for 2, 3 and 4 is a generation counter. Each start gets a number. When initialize() finishes, the code compares its number to the current one. If they differ, something released or restarted the camera in the meantime, so the result is discarded.
A complete lifecycle-aware screen
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class LifecycleCameraScreen extends StatefulWidget {
const LifecycleCameraScreen({super.key});
@override
State<LifecycleCameraScreen> createState() => _LifecycleCameraScreenState();
}
class _LifecycleCameraScreenState extends State<LifecycleCameraScreen>
with WidgetsBindingObserver {
CameraController? _controller;
CameraDescription? _description;
String? _error;
int _generation = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_start();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_release();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive) {
setState(_release);
} else if (state == AppLifecycleState.resumed && _controller == null) {
_start();
}
}
/// Invalidates any start in flight and disposes the current controller.
void _release() {
_generation++;
final controller = _controller;
_controller = null;
controller?.dispose();
}
Future<void> _start() async {
final generation = ++_generation;
CameraController? controller;
try {
if (_description == null) {
final cameras = await availableCameras();
if (cameras.isEmpty) {
if (mounted && generation == _generation) {
setState(() => _error = 'No camera found');
}
return;
}
_description = cameras.first;
}
controller = CameraController(
_description!,
ResolutionPreset.medium,
enableAudio: false,
);
await controller.initialize();
if (!mounted || generation != _generation) {
await controller.dispose();
return;
}
setState(() {
_controller = controller;
_error = null;
});
} on CameraException catch (e) {
await controller?.dispose();
if (mounted && generation == _generation) {
setState(() => _error = e.description ?? e.code);
}
}
}
Future<void> _capture(CameraController controller) async {
if (controller.value.isTakingPicture) return;
try {
final XFile file = await controller.takePicture();
debugPrint('Saved to ${file.path}');
} on CameraException catch (e) {
debugPrint('Capture failed: ${e.code}');
}
}
@override
Widget build(BuildContext context) {
final controller = _controller;
final Widget body;
if (_error != null) {
body = Center(child: Text(_error!));
} else if (controller == null) {
body = const Center(child: CircularProgressIndicator());
} else {
body = CameraPreview(controller);
}
return Scaffold(
body: body,
floatingActionButton: FloatingActionButton(
onPressed: controller == null ? null : () => _capture(controller),
child: const Icon(Icons.camera_alt),
),
);
}
}How the code works
_release()bumps_generationbefore it disposes the controller. Any_start()that is still awaiting will now see a mismatched number and clean up after itself._start()keeps the new controller in a local variable untilinitialize()succeeds. Only then is it stored in the field and shown.buildtherefore never sees a half-initialized controller.- If
initialize()throws, thecatchblock disposes the controller. Without that line, a failed initialization would leave a native session open. - On
inactive,setState(_release)clears the field and rebuilds in one step, so the preview is gone from the tree before the next frame. dispose()calls_release()directly, with nosetState, because the widget is being removed.- The
resumedbranch checks_controller == null. Aresumedevent that arrives without a precedinginactive(this can happen at startup) would otherwise start a second session.
The cached _description avoids calling availableCameras() after every resume. If you let the user switch cameras, keep the selected description here so a resume restores the camera they chose.
Failure after denial
When the user denies permission, initialize() throws a CameraException and the screen shows the error. If the user then opens Settings, grants access, and returns, the app receives resumed. Because _controller is still null, _start() runs again and clears _error on success. Retrying on resume is the behavior you want here.
Alternatives and trade-offs
| Approach | Camera held in background | Cost on resume |
|---|---|---|
| Dispose at `inactive`, recreate at `resumed` | No | Re-initialization delay, usually a fraction of a second |
| `pausePreview()` and `resumePreview()` | Yes | Almost none |
| Do nothing | Yes | None, but the session may be dead |
pausePreview() is cheap, but the app still owns the camera. Disposing is the safer default for a screen whose only job is capturing photos.
Common mistakes
- Registering the observer but never calling
removeObserver. The observer keeps a reference to yourStateand keeps receiving events after the screen is gone. - Calling
setStateafter anawaitwithout checkingmounted. - Using a
FutureBuilderover a single_initFuture. After a release, the future is complete but the controller is disposed, so the builder still renders the preview. - Disposing the controller in
pausedonly. By then another app may already have been refused the camera, and the preview may already be broken.
Exercise
A user opens your camera screen for the first time. The system permission dialog appears and the app becomes inactive while initialize() is still pending. Using the screen above, explain what happens to that first initialize() call and why the user still ends up with a working preview after tapping Allow.
Show answer
When the app goes inactive, _release() runs and increments _generation. The pending initialize() later finishes (or fails), and _start() sees that its generation no longer matches _generation. It then disposes its controller and returns without calling setState. When the user taps Allow and the app becomes resumed, _controller is still null, so _start() runs again with a new generation. Permission is now granted, initialize() succeeds, the numbers match, and the new controller is stored and shown.