Displaying YouTube video thumbnails in Flutter App in a super easy way

In one of my apps, I needed to show YouTube thumbnails for the link to the YouTube video. YouTube Video contains a video ID that can be used to fetch the thumbnail associated with that particular video.

For example

https://youtu.be/x96iLmXqRYk

The part after v= is x96iLmXqRYk which is called video id.

After this One this that we need is a magic link which fetch the thumbnail

http://img.youtube.com/vi/"+videoID+"/0.jpg

lets replace it with our example video id

http://img.youtube.com/vi/x96iLmXqRYk/0.jpg

To test it just click on above link to see the magic.

One more important thing we can replace 0.jpg

with 1.jpg and so on if video contains more than one thumbnail but in most of the cases we need only primary thumbnail.

In Flutter, If you have video Id then you can directly use this method to fetch thumbnail.

String getYoutubeThumbnailFromID(String videoID) {
    return 'https://img.youtube.com/vi/$videoID/0.jpg';
  }  

In case if you have the URL of the video , below code can be used to fetch video id from URL of the the YouTube video

String getYoutubeThumbnail(String videoUrl) {
    String? videoID = getYoutubeVideoIdFromUrl(videoUrl);
    return videoID == null ? 'ANY_PLACEHOLDER IMAGE URL' : 'https://img.youtube.com/vi/$videoID/0.jpg';
  }   

This is calling below code to extract the video id from url.

String? getYoutubeVideoIdFromUrl(String url, {bool trimWhitespaces = true}) {
    if (!url.contains("http") && (url.length == 11)) return url;
    if (trimWhitespaces) url = url.trim();

    for (var exp in [
      RegExp(
          r"^https:\/\/(?:www\.|m\.)?youtube\.com\/watch\?v=([_\-a-zA-Z0-9]{11}).*$"),
      RegExp(
          r"^https:\/\/(?:music\.)?youtube\.com\/watch\?v=([_\-a-zA-Z0-9]{11}).*$"),
      RegExp(
          r"^https:\/\/(?:www\.|m\.)?youtube\.com\/shorts\/([_\-a-zA-Z0-9]{11}).*$"),
      RegExp(
          r"^https:\/\/(?:www\.|m\.)?youtube(?:-nocookie)?\.com\/embed\/([_\-a-zA-Z0-9]{11}).*$"),
      RegExp(r"^https:\/\/youtu\.be\/([_\-a-zA-Z0-9]{11}).*$")
    ]) {
      Match? match = exp.firstMatch(url);
      if (match != null && match.groupCount >= 1) return match.group(1);
    }

    return null;
  }
}

This is how you fetch Youtube thumbnail in Flutter. Thanks a lot for your time.

Leave a Reply