Sub topic 15
Recording video
This chapter covers recording video with the camera plugin and with image_picker, and what to do with the file afterward. It assumes you have finished the earlier chapters on platform setup, XFile, and CameraController initialization, preview, and lifecycle. You should be comfortable with StatefulWidget, async/await, and try/on blocks.
Two ways to get a video
Video follows the same split as photos. image_picker hands the job to the system camera app. camera records inside your own UI.
| Need | Use | Why |
|---|---|---|
| "Attach a clip" with a time limit | `image_picker` | No controller, no preview, no lifecycle code |
| Custom recording screen, overlays, timer | `camera` | You own the UI and the controller |
| Pause and resume while recording | `camera` | The system camera app does not expose this to you |
| Pick an existing video from the gallery | `image_picker` | `camera` only records |
If a system camera app is acceptable, prefer it. It handles permissions, storage, and device quirks for you.
Recording with image_picker
pickVideo mirrors pickImage. It returns an XFile, or null if the user cancels.
import 'package:image_picker/image_picker.dart';
final ImagePicker _picker = ImagePicker();
Future<XFile?> recordShortClip() {
return _picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 30),
);
}
Future<XFile?> pickVideoFromGallery() {
return _picker.pickVideo(source: ImageSource.gallery);
}maxDuration asks the system camera to stop at that length. Treat it as a request, not a guarantee. Some Android camera apps ignore it, so check the duration on the server or after playback loads if the limit matters.
On iOS, ImageSource.camera needs NSCameraUsageDescription. A clip recorded with sound also needs NSMicrophoneUsageDescription. Both are in the platform setup chapter.
The recording API in camera
A CameraController exposes four video methods:
startVideoRecording()begins recording to a temporary file.pauseVideoRecording()andresumeVideoRecording()suspend and continue the same file.stopVideoRecording()finishes the file and returns anXFile.
The controller reports state through controller.value, a CameraValue. Two fields matter here:
isRecordingVideoistruefrom start until stop, including while paused.isRecordingPausedistrueonly while paused.
Because CameraController is a ValueNotifier<CameraValue>, you can rebuild buttons from it with ValueListenableBuilder instead of tracking your own booleans.
Audio is decided at construction
The enableAudio argument is set when you create the controller. It defaults to true. If you pass false, the clip has no sound and the microphone permission is never requested. You cannot change it later without creating a new controller.
Audio adds a second permission prompt (microphone) after the camera prompt. If the user denies only the microphone, initialize() throws a CameraException, as described in the error-handling chapter. If sound is optional in your app, catch that case and retry with enableAudio: false.
A recording screen
This screen shows the preview, a start/stop button, a pause/resume button, and an elapsed-time counter. It also prints the recorded file path.
import 'dart:async';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class VideoRecorderScreen extends StatefulWidget {
const VideoRecorderScreen({super.key, required this.camera});
final CameraDescription camera;
@override
State<VideoRecorderScreen> createState() => _VideoRecorderScreenState();
}
class _VideoRecorderScreenState extends State<VideoRecorderScreen> {
late final CameraController _controller;
late final Future<void> _initFuture;
Timer? _ticker;
Duration _elapsed = Duration.zero;
XFile? _lastVideo;
@override
void initState() {
super.initState();
_controller = CameraController(
widget.camera,
ResolutionPreset.high,
enableAudio: true,
);
_initFuture = _controller.initialize();
}
@override
void dispose() {
_ticker?.cancel();
_controller.dispose();
super.dispose();
}
Future<void> _start() async {
try {
await _controller.startVideoRecording();
_elapsed = Duration.zero;
_ticker = Timer.periodic(const Duration(seconds: 1), (_) {
if (!_controller.value.isRecordingPaused) {
setState(() => _elapsed += const Duration(seconds: 1));
}
});
setState(() {});
} on CameraException catch (e) {
debugPrint('Start failed ${e.code}: ${e.description}');
}
}
Future<void> _stop() async {
_ticker?.cancel();
try {
final XFile file = await _controller.stopVideoRecording();
setState(() => _lastVideo = file);
debugPrint('Video saved to ${file.path}');
} on CameraException catch (e) {
debugPrint('Stop failed ${e.code}: ${e.description}');
}
}
Future<void> _togglePause() async {
try {
if (_controller.value.isRecordingPaused) {
await _controller.resumeVideoRecording();
} else {
await _controller.pauseVideoRecording();
}
} on CameraException catch (e) {
debugPrint('Pause toggle failed ${e.code}: ${e.description}');
}
}
String _format(Duration d) {
final m = d.inMinutes.toString().padLeft(2, '0');
final s = (d.inSeconds % 60).toString().padLeft(2, '0');
return '$m:$s';
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return const Center(child: Text('Camera unavailable'));
}
return Stack(
fit: StackFit.expand,
children: [
CameraPreview(_controller),
Positioned(
top: 48,
left: 0,
right: 0,
child: Center(
child: Text(
_format(_elapsed),
style: const TextStyle(color: Colors.white, fontSize: 24),
),
),
),
Positioned(
bottom: 32,
left: 0,
right: 0,
child: ValueListenableBuilder<CameraValue>(
valueListenable: _controller,
builder: (context, value, _) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (value.isRecordingVideo)
IconButton(
iconSize: 40,
color: Colors.white,
onPressed: _togglePause,
icon: Icon(
value.isRecordingPaused
? Icons.play_arrow
: Icons.pause,
),
),
IconButton(
iconSize: 64,
color: Colors.red,
onPressed: value.isRecordingVideo ? _stop : _start,
icon: Icon(
value.isRecordingVideo
? Icons.stop_circle
: Icons.fiber_manual_record,
),
),
],
);
},
),
),
if (_lastVideo != null)
Positioned(
bottom: 120,
left: 16,
right: 16,
child: Text(
'Last clip: ${_lastVideo!.name}',
style: const TextStyle(color: Colors.white),
),
),
],
);
},
),
);
}
}The ticker skips increments while paused, so the displayed time matches the length of the clip. A timer that ignored pausing would drift away from the real duration.
Lifecycle: stop before you release
The lifecycle chapter showed that you should dispose the controller on AppLifecycleState.inactive. With video, add one step: stop the recording first. Disposing a controller mid-recording can leave you with a truncated or unusable file, and the call fails if the camera is already torn down.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive &&
_controller.value.isInitialized &&
_controller.value.isRecordingVideo) {
_stop();
}
}This assumes the State mixes in WidgetsBindingObserver and has called addObserver(this) in initState. In a full screen, call this stop logic before the dispose-and-recreate code from the lifecycle chapter. Phone calls, notification shade pulls on some Android versions, and the app switcher all trigger inactive.
Handling the finished file
stopVideoRecording() returns an XFile that points into a temporary or cache directory. The system can delete it, and a cache clear will. Copy it before you rely on it.
import 'package:camera/camera.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<String> keepVideo(XFile recorded) async {
final dir = await getApplicationDocumentsDirectory();
final target = p.join(
dir.path,
'clip_${DateTime.now().millisecondsSinceEpoch}.mp4',
);
await recorded.saveTo(target);
return target;
}The extension is chosen by you, so match it to what the platform wrote. Android and iOS commonly produce MP4 and MOV respectively, so inspect recorded.path or recorded.mimeType rather than assuming. Uploading works as in the file-handling chapter: stream the file with MultipartFile.fromPath or equivalent, and do not read a whole video into memory with readAsBytes().
Common errors
- Recording starts but the clip has no sound. The controller was created with
enableAudio: false, or the microphone permission was denied. - Crash on iOS when starting.
NSMicrophoneUsageDescriptionis missing fromInfo.plist. startVideoRecordingthrows because a recording is already in progress. A double tap called it twice. Disable the button whileisRecordingVideoistrue, as the screen does.- The file disappears later. You kept the temporary path. Copy it with
saveToas soon as you get it. - Preview freezes after returning from the background. The controller was not recreated after a dispose on
inactive.
Verifying on devices
The simulator and emulator cameras produce synthetic frames and often no usable audio. Test on at least one physical Android and one physical iPhone. Check each of these:
- Record, stop, and play the file back with sound.
- Record, pause, resume, stop, and confirm the length excludes the pause.
- Start recording, then switch apps, and confirm the clip is saved or the app recovers cleanly.
- Deny the microphone permission and confirm your fallback runs.
Exercise
A user taps record, then receives a phone call. Your screen disposes the controller on AppLifecycleState.inactive, and the clip is corrupted. What change fixes this, and which controller field tells you it is needed?
Show answer
Call stopVideoRecording() before disposing the controller. Check controller.value.isRecordingVideo: if it is true, stop the recording and keep or copy the returned XFile first, then dispose and later recreate the controller on resumed.
Exercise
Your app records video with enableAudio: true. The user allows the camera but denies the microphone, and initialize() throws a CameraException. How can you still let the user record?
Show answer
Catch the CameraException, dispose the failed controller, and create a new CameraController with enableAudio: false. Then initialize it and show a note that the clip will be silent. The enableAudio flag cannot be changed on an existing controller.