media-kit icon indicating copy to clipboard operation
media-kit copied to clipboard

Null check operator used on a null value

Open SamAAdd opened this issue 1 year ago • 1 comments

I'm getting this exception report in my sentry logs when the user plays a video on Android after having initialised the package in main.dart:

MediaKitVideoPlayer.buildView (package:video_player_media_kit/src/media_kit_video_player.dart:178)

I wonder if it's due to the forced usage of the Videocontroller below? There is a point in my code where i'm disposing of the video controller then creating a new one.

@override
  Widget buildView(int textureId) {
    return Video(
      key: ValueKey(_videoControllers[textureId]!),
      controller: _videoControllers[textureId]!,
      wakelock: false,
      controls: NoVideoControls,
      fill: const Color(0x00000000),
      pauseUponEnteringBackgroundMode: false,
      resumeUponEnteringForegroundMode: false,
    );
  }

May I suggest that we update this to the following?

@override
  Widget buildView(int textureId) {
    final controller = _videoControllers[textureId];
    if (controller == null) {
      // Handle the error gracefully, e.g., show an error widget or a placeholder
      return Center(
        child: Text('Video controller not found for textureId: $textureId'),
      );
    }
    return Video(
      key: ValueKey(controller),
      controller: controller,
      wakelock: false,
      controls: NoVideoControls,
      fill: const Color(0x00000000),
      pauseUponEnteringBackgroundMode: false,
      resumeUponEnteringForegroundMode: false,
    );
  }

SamAAdd avatar Dec 16 '24 09:12 SamAAdd

I think you can optimize this in your app by ensuring the video player is not disposed of until it is completely out of view. Here's an example implementation:

Code Example:

void initPlayer() {
  // Store the references to the old controller 
  VideoPlayerController? oldController = controller;

  // Initialize the new video player controller based on the quality type
  if (_quality.value.isFile) {
    controller = VideoPlayerController.file(
      File(_quality.value.file!.path),
      httpHeaders: _quality.value.httpHeaders ?? {},
    );
  } else {
    controller = VideoPlayerController.networkUrl(
      Uri.parse(_quality.value.url!),
      httpHeaders: _quality.value.httpHeaders ?? {},
    );
  }

  // Update the UI to reflect the new controller
  setState(() {});

  // Dispose of the old controller after the update
  oldController?.dispose();
}

abdelaziz-mahdy avatar Dec 24 '24 17:12 abdelaziz-mahdy