1

I've a ListView of posts each post can contain a youtube video so I used youtube_player_flutter package to render the youtube video on each post.

The problem happened on scrolling the ListView it became laggy and slow after adding the youtube player. Also I've noticed that the placed youtube videos are loaded automatically on building the list even if I've disabled the autoPlay tag.

  ListView.builder(
    itemCount: posts.length,
    itemBuilder: (_, i) => const YoutubePlayerWidget(videoUrl: posts[i].video!),
  );

class YoutubePlayerWidget extends StatefulWidget {
  final String? videoId;
  final String? videoUrl;

  const YoutubePlayerWidget({super.key, this.videoId, this.videoUrl});

  @override
  State<YoutubePlayerWidget> createState() => _YoutubePlayerWidgetState();
}

class _YoutubePlayerWidgetState extends State<YoutubePlayerWidget> {
  late YoutubePlayerController _controller;

  @override
  initState() {
    _controller = YoutubePlayerController(
      initialVideoId: widget.videoId ?? YoutubePlayer.convertUrlToId(widget.videoUrl!)!,
      flags: const YoutubePlayerFlags(
        autoPlay: false,
        mute: true,
        isLive: false,
        disableDragSeek: true,
        loop: false,
        forceHD: false,
      ),
    );
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return YoutubePlayer(controller: _controller);
  }
} 

1 Answers1

0

You need some workaround here to optimise the list.

  • Instead of adding the player into each listView items, replace the video player with the thumbnail image.

  • Add gestureDetector on the image to get the details of video and show the video player and relevant widgets over the same image using Stack widget where hide the Video player with a boolean conditional so that it DOES NOT appear in the Widget tree initially.

     Stack(
       children: [
          Image.network('youtube-thumbnail-url'),
          Positioned(
            child: YoutubePlayerWidget(
            videoUrl: posts[i].video!,
             ),
          )
       ],
     ),
    

Manage the position of the video player using the Positioned widget. You may try with Positioned.fill as well depending on your requirement.

How to get the thumbnail image from the video id:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg

To optimise the thumbnail path take help of this post

Get Thumbnail of YouTube Videos