setScreenShareEnabled method

Future<void> setScreenShareEnabled(
  1. bool enabled, {
  2. MediaDisplayDetails? device,
})

Enables/disables local screen-sharing stream based on enabled.

Implementation

Future<void> setScreenShareEnabled(
  bool enabled, {
  MediaDisplayDetails? device,
}) async {
  Log.debug(
    'setScreenShareEnabled($enabled, ${device?.deviceId()})',
    '$runtimeType',
  );

  switch (screenShareState.value) {
    case LocalTrackState.disabled:
    case LocalTrackState.disabling:
      if (enabled) {
        screenShareState.value = LocalTrackState.enabling;
        try {
          await _updateSettings(screenDevice: device ?? displays.firstOrNull);
          await _room?.enableVideo(MediaSourceKind.display);
          screenShareState.value = LocalTrackState.enabled;

          final List<LocalMediaTrack> tracks = await MediaUtils.getTracks(
            screen: ScreenPreferences(device: screenDevice.value?.deviceId()),
          );
          tracks.forEach(_addLocalTrack);
        } on MediaStateTransitionException catch (_) {
          // No-op.
        } on LocalMediaInitException catch (e) {
          screenShareState.value = LocalTrackState.disabled;
          if (!e.message().contains('Permission denied')) {
            addError('enableScreenShare() call failed with $e');
            rethrow;
          }
        } catch (e) {
          screenShareState.value = LocalTrackState.disabled;
          addError('enableScreenShare() call failed with $e');
          rethrow;
        }
      }
      break;

    case LocalTrackState.enabled:
    case LocalTrackState.enabling:
      if (!enabled) {
        screenShareState.value = LocalTrackState.disabling;
        try {
          await _room?.disableVideo(MediaSourceKind.display);
          _removeLocalTracks(MediaKind.video, MediaSourceKind.display);
          screenShareState.value = LocalTrackState.disabled;
          screenDevice.value = null;
        } on MediaStateTransitionException catch (_) {
          // No-op.
        } catch (e) {
          addError('disableScreenShare() call failed with $e');
          screenShareState.value = LocalTrackState.enabled;
          rethrow;
        }
      }
      break;
  }
}