switchCamera method

Future<bool> switchCamera({
  1. String? deviceId,
})

a utility method which can be used to switch camera of user device if it has more than one camera deviceId : device id of the camera you want to switch to deviceId is important for switchCamera to work in browsers.

Implementation

Future<bool> switchCamera({String? deviceId}) async {
  List<MediaDeviceInfo> videoDevices = await getVideoInputDevices();
  if (videoDevices.isEmpty) {
    throw Exception("No Camera Found");
  }
  if (kIsWeb) {
    if (deviceId == null) {
      _context._logger.finest(
          'deviceId not provided,hence switching to default last deviceId should be of back camera ideally');
      deviceId = videoDevices.last.deviceId;
    }
    await _disposeMediaStreams(ignoreRemote: true);
    webRTCHandle!.localStream = await navigator.mediaDevices.getUserMedia({
      'video': {
        'deviceId': {'exact': deviceId}
      },
      'audio': true
    });
    List<RTCRtpSender> senders =
        (await webRTCHandle!.peerConnection!.getSenders());
    webRTCHandle!.localStream?.getTracks().forEach((element) async {
      senders.forEach((sender) async {
        if (sender.track?.kind == element.kind) {
          await sender.replaceTrack(element);
        }
      });
    });
    return true;
  } else {
    if (webRTCHandle?.localStream != null) {
      _context._logger.finest(
          'using helper to switch camera, only works in android and ios');
      return Helper.switchCamera(
          webRTCHandle!.localStream!.getVideoTracks().first);
    }
    return false;
  }
}