openCamera static method

Future<String?> openCamera(
  1. BuildContext context, {
  2. bool allowGallery = true,
})

Open the full-screen camera preview. allowGallery — whether to show the gallery button in the camera UI.

Implementation

static Future<String?> openCamera(
  BuildContext context, {
  bool allowGallery = true,
}) async {
  try {
    // Location: do not block the camera if permission is denied,
    // the preview page can show a warning if needed.
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      await Geolocator.requestPermission();
    }

    // Cameras
    final cameras = await availableCameras();
    if (cameras.isEmpty) {
      throw Exception('No cameras available on this device.');
    }

    // Controller lifecycle is handled by CameraPreviewPage.
    final resultPath = await Navigator.of(context).push<String>(
      MaterialPageRoute(
        builder: (_) => CameraPreviewPage(
          cameras: cameras,
          allowGallery: allowGallery,
        ),
      ),
    );

    return resultPath;
  } catch (e) {
    debugPrint('Error opening camera: $e');
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to open camera: $e')),
      );
    }
    return null;
  }
}