extract video id from youtube url flutter code example

Example 1: get youtube video id from url flutter

/// If videoId is passed as url then no conversion is done.
  static String? convertUrlToId(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:\/\/(?: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;
  }

Example 2: How to extract video id from youtube link in flutter

//Example of links
final urls = [
  'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
  'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
  'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
  'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
  'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
  'http://www.youtube.com/watch?v=0zM3nApSvMg',
  'http://youtu.be/0zM3nApSvMg',
];

String getYoutubeVideoId(String Url) {
  RegExp regExp = new RegExp(
    r'.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*',
    caseSensitive: false,
    multiLine: false,
  );
final match = regExp.firstMatch(url).group(1); // <- This is the fix
String str = match;
return str;
}

Tags:

Dart Example