Sub topic 12
Handling pause, resume, and disposal
This chapter assumes you know Dart async and await, Flutter StatefulWidget lifecycle methods, and how to add the camera package. A CameraController owns a connection to a hardware camera. Your state object must release that connection when the app leaves the foreground and create it again when the app returns.
Why lifecycle handling matters
The camera is a shared operating-system resource. Another app may need it while your app is in the background. Keeping a controller alive can cause camera errors, battery use, or a black preview after the app resumes.
The camera plugin does not automatically manage every application lifecycle transition. Use WidgetsBindingObserver to receive those transitions:
inactivemeans the app temporarily lost focus.pausedmeans the app is in the background.resumedmeans the app is active again.disposemeans the screen is permanently leaving the widget tree.
A useful policy is to dispose of the controller for inactive and paused, then initialize a new controller for resumed.
Observe lifecycle changes
The following screen registers as an observer, releases the controller when needed, and initializes it again after resume. Setting _controller to null before disposal makes repeated lifecycle events safe.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CameraPage extends StatefulWidget {
const CameraPage({super.key});
@override
State<CameraPage> createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage>
with WidgetsBindingObserver {
CameraController? _controller;
Future<void>? _initializeFuture;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_initializeFuture = _initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
if (cameras.isEmpty) {
throw StateError('No camera is available');
}
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);
_controller = controller;
try {
await controller.initialize();
} on CameraException {
if (identical(_controller, controller)) {
_controller = null;
}
await controller.dispose();
rethrow;
}
}
void _releaseCamera() {
final controller = _controller;
_controller = null;
controller?.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused) {
_releaseCamera();
} else if (state == AppLifecycleState.resumed &&
_controller == null &&
mounted) {
setState(() {
_initializeFuture = _initializeCamera();
});
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_releaseCamera();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError || _controller == null) {
return const Center(child: Text('Camera unavailable'));
}
return CameraPreview(_controller!);
},
),
);
}
}Common lifecycle errors
Do not reuse a disposed controller. Create a new CameraController after resume. Do not call setState after an asynchronous initialization finishes if the widget has already been removed. Check mounted before updating state.
Also remove the observer in dispose. Otherwise the state object can continue receiving lifecycle notifications after its screen has gone away.
Exercise
Why should the app create a new CameraController after returning from the background instead of reusing the old one?
Show answer
The old controller was disposed to release the camera resource. A disposed controller cannot safely initialize or capture again, so the app must create and initialize a new controller.