91 lines
2.2 KiB
Dart
91 lines
2.2 KiB
Dart
import 'package:camera/camera.dart';
|
|
import 'package:permission_handler/permission_handler.dart';
|
|
|
|
class CameraService {
|
|
CameraController? _controller;
|
|
List<CameraDescription>? _cameras;
|
|
bool _isInitialized = false;
|
|
|
|
bool get isInitialized => _isInitialized;
|
|
CameraController? get controller => _controller;
|
|
|
|
Future<bool> requestPermissions() async {
|
|
final cameraStatus = await Permission.camera.request();
|
|
return cameraStatus.isGranted;
|
|
}
|
|
|
|
Future<bool> initializeCamera() async {
|
|
try {
|
|
// Request camera permissions
|
|
final hasPermission = await requestPermissions();
|
|
if (!hasPermission) {
|
|
return false;
|
|
}
|
|
|
|
// Get available cameras
|
|
_cameras = await availableCameras();
|
|
if (_cameras == null || _cameras!.isEmpty) {
|
|
return false;
|
|
}
|
|
|
|
// Initialize the back camera (first camera is usually the back one)
|
|
_controller = CameraController(
|
|
_cameras!.first,
|
|
ResolutionPreset.high,
|
|
enableAudio: false,
|
|
);
|
|
|
|
await _controller!.initialize();
|
|
_isInitialized = true;
|
|
return true;
|
|
} catch (e) {
|
|
print('Error initializing camera: $e');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
Future<String?> captureImage() async {
|
|
if (_controller == null || !_isInitialized) {
|
|
print('Camera not initialized');
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
final image = await _controller!.takePicture();
|
|
return image.path;
|
|
} catch (e) {
|
|
print('Error capturing image: $e');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<void> dispose() async {
|
|
await _controller?.dispose();
|
|
_controller = null;
|
|
_isInitialized = false;
|
|
}
|
|
|
|
Future<void> switchCamera() async {
|
|
if (_cameras == null || _cameras!.length < 2) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
final currentCameraIndex = _cameras!.indexOf(_controller!.description);
|
|
final nextCameraIndex = (currentCameraIndex + 1) % _cameras!.length;
|
|
|
|
await _controller?.dispose();
|
|
|
|
_controller = CameraController(
|
|
_cameras![nextCameraIndex],
|
|
ResolutionPreset.high,
|
|
enableAudio: false,
|
|
);
|
|
|
|
await _controller!.initialize();
|
|
} catch (e) {
|
|
print('Error switching camera: $e');
|
|
}
|
|
}
|
|
}
|