Getting youtube video details in flutter/dart

Viewed 3407

I am using youtube_player_flutter: ^6.1.0+4 plugin to play YouTube videos, how can I extract the details of the video ...like duration and size

import 'package:youtube_player_flutter/youtube_player_flutter.dart';

YoutubePlayerController _youtubecontroller = YoutubePlayerController():
   YoutubePlayer(
     controller: _youtubecontroller,
     showVideoProgressIndicator: true,
   ),
1 Answers

You can do a http request with YouTube embed URL and get the info in JSON.

https://www.youtube.com/oembed?url=<youtube-video_url_here>&format=json

It has some info in it such as thumbnail URL, width, height, etc.

For example:

import 'package:http/http.dart' as http;

Future<dynamic> getDetail(String userUrl) async {
    String embedUrl = "https://www.youtube.com/oembed?url=$userUrl&format=json";

    //store http request response to res variable
    var res = await http.get(embedUrl);
    print("get youtube detail status code: " + res.statusCode.toString());

    try {
      if (res.statusCode == 200) {
        //return the json from the response
        return json.decode(res.body);

      } else {
        //return null if status code other than 200
        return null;
      }
    } on FormatException catch (e) {
      print('invalid JSON'+ e.toString());
      //return null if error
      return null;
    }
  }

Example how to use the function:

String videoUrl = 'https://www.youtube.com/watch?v=d_m5csmrf7I';
var jsonData = await getDetail(videoUrl);
//you can take anything provided in the JSON, just change the key according to
//what is available in the response
String title = jsonData['title'];

Open this link in your browser to see the data you get in JSON: https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=d_m5csmrf7I&format=json

Related