Sub topic 8
Listing the device cameras
Before you can show a live preview, you need to know which cameras the device has. The camera plugin answers that with one call, availableCameras(). This chapter covers what that call returns, how to pick a camera from the result, and what can go wrong.
This chapter assumes you have read the platform setup chapter, so camera permissions are already declared for Android and iOS. It also assumes you are comfortable with async/await, Future, and StatefulWidget lifecycle methods.
What availableCameras returns
availableCameras() is a top-level function in package:camera/camera.dart. It returns a Future<List<CameraDescription>>. Each CameraDescription describes one physical or logical camera and has three fields:
| Field | Type | Meaning |
|---|---|---|
| `name` | `String` | A platform-specific identifier for the camera. Treat it as opaque. |
| `lensDirection` | `CameraLensDirection` | `front`, `back`, or `external`. |
| `sensorOrientation` | `int` | Degrees (0, 90, 180, or 270) the sensor image is rotated relative to the device's natural orientation. |
A CameraDescription is a plain description. It does not open the camera, hold any resource, or need to be disposed. Calling availableCameras() does not trigger a permission prompt on its own. The prompt appears when you initialize a CameraController, which a later chapter covers.
import 'package:camera/camera.dart';
import 'package:flutter/widgets.dart';
Future<void> printCameras() async {
WidgetsFlutterBinding.ensureInitialized();
final List<CameraDescription> cameras = await availableCameras();
for (final camera in cameras) {
debugPrint(
'${camera.name}: ${camera.lensDirection.name}, '
'sensor ${camera.sensorOrientation} degrees',
);
}
}The call to WidgetsFlutterBinding.ensureInitialized() matters. availableCameras() talks to the platform through a plugin channel, and channels need the binding to exist. If you call the function from main() before runApp, you must initialize the binding first. Otherwise you get an error about the binary messenger not being ready.
Where to call it
You have two common choices. Both are valid, and they trade simplicity against flexibility.
- In
main(), beforerunApp. You fetch the list once and pass it down to the screens that need it. - Inside the camera screen, as the first step of your setup.
The first approach looks like this:
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
late List<CameraDescription> _cameras;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
_cameras = await availableCameras();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Text('Cameras found: ${_cameras.length}'),
),
),
);
}
}This is short, but it has costs. The app delays its first frame until the platform answers. A global late variable is also awkward to test. If the call throws, the app never starts.
The second approach keeps the failure local to the screen that needs the camera. The chapter on initializing a CameraController uses it, because the screen can then show an error message instead of crashing at startup. Prefer it unless many screens need the list.
Choosing a camera
The list has no guaranteed order. Many apps use cameras.first and it usually works, but it is a guess. On most phones the back camera comes first, and that is a convention, not a promise. If your feature needs a specific lens, search by lensDirection.
import 'package:camera/camera.dart';
CameraDescription? pickCamera(
List<CameraDescription> cameras,
CameraLensDirection direction,
) {
for (final camera in cameras) {
if (camera.lensDirection == direction) {
return camera;
}
}
return null;
}The function returns null when no camera matches. That is deliberate. A tablet may have only a front camera. A laptop running Flutter on desktop may have an external webcam. An emulator may have a single virtual camera. Your caller decides what to do, for example fall back to any camera or show a message.
A common pattern is to prefer the back camera and fall back to whatever exists:
import 'package:camera/camera.dart';
CameraDescription chooseDefaultCamera(List<CameraDescription> cameras) {
return pickCamera(cameras, CameraLensDirection.back) ?? cameras.first;
}This still throws a StateError if cameras is empty, so check that first, as the next section explains.
Handling an empty list
availableCameras() returns an empty list when the device has no usable camera. This is normal on some emulators, some Android TV and Chromebook devices, and a few desktop machines. It is not an error, so no exception is thrown. If you call cameras.first on the empty list, you get a StateError with the message "No element".
Check for emptiness explicitly:
import 'package:camera/camera.dart';
Future<CameraDescription?> findCamera() async {
final cameras = await availableCameras();
if (cameras.isEmpty) {
return null;
}
return cameras.firstWhere(
(c) => c.lensDirection == CameraLensDirection.back,
orElse: () => cameras.first,
);
}Returning null pushes the "no camera" decision to the UI, where you can offer the gallery picker from image_picker as an alternative. That is a good fit for the choice discussed in the first chapter of this tutorial.
Handling errors from the call
availableCameras() can throw a CameraException. This is rare, but it happens when the platform cannot enumerate cameras, for example due to a plugin or device fault. Catch it where you call the function.
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
Future<List<CameraDescription>> loadCameras() async {
try {
return await availableCameras();
} on CameraException catch (e) {
debugPrint('Could not list cameras: ${e.code} ${e.description}');
return const <CameraDescription>[];
}
}Returning an empty list on failure lets the rest of your code use one path for "no cameras", whether the cause is missing hardware or a failed call. If you need to tell the two cases apart, for instance to show a retry button, return a result type or rethrow instead.
Why the lens direction and sensor orientation matter
Two fields influence what your user sees.
lensDirection controls mirroring and user expectations. People expect a front-camera preview to look like a mirror and a back-camera preview to look like a window. The plugin handles the preview mirroring for you. You mostly use lensDirection to decide which camera to open and which icon to show on a "switch camera" button.
sensorOrientation explains why raw sensor data can look rotated. Android sensors are usually mounted at 90 degrees (back) or 270 degrees (front) relative to the device's natural portrait orientation. CameraPreview compensates for this. You only need the value yourself if you process raw frames, for example from an image stream, and rotate them manually.
The shape of the whole flow
The diagram below shows how the cameras list feeds the rest of the camera setup.
Common mistakes
- Skipping
WidgetsFlutterBinding.ensureInitialized()when calling frommain(). The symptom is an error that the binary messenger or plugin channel is unavailable. - Calling
cameras.firston an empty list. Test on an emulator with no camera configured to see this. - Assuming the list order.
firstis the back camera on most phones, not all devices. - Caching the list forever. External cameras such as USB webcams can appear or disappear while the app runs. If your app supports them, call
availableCameras()again when the user opens the camera screen. - Expecting a permission prompt. Listing cameras does not request permission. Denial shows up later, when you initialize the controller.
- Treating
nameas stable or readable. It is a platform identifier. Do not show it to users or store it as a long-term preference. Store thelensDirectioninstead.
Practice
Exercise
Your app calls availableCameras() and then uses cameras.first to create a controller. It crashes with "Bad state: No element" on an Android emulator. What is the cause, and how do you fix it?
Show answer
The emulator has no camera configured, so availableCameras() returned an empty list without throwing. Calling first on an empty list throws a StateError. Check cameras.isEmpty before choosing a camera, and show a fallback such as the image_picker gallery or an explanatory message when the list is empty.
Exercise
Write a function Future<CameraDescription?> findFront() that returns the front camera, or null if none exists. Also state what it should do when availableCameras() throws a CameraException.
Show answer
Example: Future<CameraDescription?> findFront() async { try { final cameras = await availableCameras(); for (final c in cameras) { if (c.lensDirection == CameraLensDirection.front) return c; } return null; } on CameraException { return null; } } Catching CameraException and returning null treats a failed call like a missing camera, so the caller has one path to handle. If the UI needs to distinguish the two cases, for example to offer a retry, rethrow or return a result type instead.
Exercise
Why is it a poor idea to store CameraDescription.name as the user's preferred camera in saved settings?
Show answer
The name is an opaque, platform-specific identifier. It can differ between devices, OS versions, and plugin versions, and it may change when external cameras are connected or removed. Store a stable value such as the lensDirection and look up the matching description at runtime.