CameraController
- Flutter course
- Advanced
- Lesson 34/69
- 4 min
Take a photo with CameraController.
Taking photos with CameraController
After the CameraController is initialized, you capture a photo with the takePicture method. This method asynchronously returns an XFile. The path of the captured photo is obtained with file.path.
final file = await controller.takePicture();
print(file.path);The dispose method
When the CameraController is no longer needed, you release its resources with dispose. Because camera hardware is a limited resource, not disposing the controller causes memory and hardware leaks. It is called in the dispose method of stateful widgets.
@override
void dispose() {
controller.dispose();
super.dispose();
}Practice Take a photo and print it
Create a CameraController, initialize it with initialize, capture a photo with takePicture and print the file path.
Starter code
class CameraDescription {
final String name;
CameraDescription(this.name);
}
enum ResolutionPreset { low, medium, high }
class XFile {
final String path;
XFile(this.path);
}
class CameraController {
final CameraDescription camera;
final ResolutionPreset resolution;
CameraController(this.camera, this.resolution);
Future<void> initialize() async {}
Future<XFile> takePicture() async => XFile('/tmp/photo.png');
void dispose() {}
}
void main() async {
// controller oluştur ve başlat
// fotoğraf çek, dosya yolunu yazdır
// dispose çağır
}Sample solution
class CameraDescription {
final String name;
CameraDescription(this.name);
}
enum ResolutionPreset { low, medium, high }
class XFile {
final String path;
XFile(this.path);
}
class CameraController {
final CameraDescription camera;
final ResolutionPreset resolution;
CameraController(this.camera, this.resolution);
Future<void> initialize() async {}
Future<XFile> takePicture() async => XFile('/tmp/photo.png');
void dispose() {}
}
void main() async {
final controller = CameraController(
CameraDescription('0'),
ResolutionPreset.high,
);
await controller.initialize();
final file = await controller.takePicture();
print(file.path);
controller.dispose();
}Expected output
/tmp/photo.png
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the takePicture method return?
- Future<void>
- Future<XFile> Correct answer
- Future<int>
- Future<Widget>
Explanation: takePicture asynchronously returns an XFile; this file contains the path of the captured photo.
2 Take a picture
final file = await controller.____;
final file = await controller.takePicture();
Explanation: To capture a photo you call the takePicture method; it is called with parentheses and awaited.
3 CameraController parts
| Term | Meaning |
|---|---|
takePicture |
Takes a photo |
XFile |
Captured file |
dispose |
Releases resources |
initialize |
Initialization |