如何从YouTube播放列表的下一页中快速获取数据?

时间:2019-06-17 15:46:02

标签: flutter

我尝试过使用pageToken,但是问题是当前50个元素添加到视频列表中时,之后的50个元素未添加。显示前50个数据后应该获取下50个元素时,它显示错误:         RangeError(索引):无效值:不在0..28范围内,包括:50 如果能得到解决方案,我将非常感谢,谢谢。

class _PlaylistPageState extends State<PlaylistPage> {
  bool isMore = false;
  Map data = new Map();
  List<dynamic> videos = new List();

getData() async {
    String baseUrl =
        "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${widget.plist}" +
            "&maxResults=50&key=" +
            "AIzaSyCrrzqrXMfI8xpD0a5wdU1xDcc7QTUjLSA";
    String nextPageUrl =
        "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${widget.plist}" +
            "&maxResults=50&pageToken=CDIQAA&key=" +
            "AIzaSyCrrzqrXMfI8xpD0a5wdU1xDcc7QTUjLSA";

    var baseResponse;
    var nextPageResponse;
    if(!isMore){
      baseResponse = await http.get(baseUrl);
    } else {
      nextPageResponse = await http.get(nextPageUrl);
    }


      setState(() {
        if(!isMore){
          videos.add(json.decode(baseResponse.body)["items"]);
        } else {
          videos.add(json.decode(nextPageResponse.body)["items"]);
        }
      });
  }

  fetchTen(){
    for(int i = 0; i < 10; i++){
      getData();
    }
  }

 ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();
    fetchTen();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if(videos.length == 50){
          setState(() {
            isMore = true;
          });
        }
        //print(videos.length);
        fetchTen();
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(
          child:ListView.builder(
              controller: _scrollController,
              itemCount: videos == null ? 0 : videos.length,
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Material(
                    elevation: 8.0,
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: 200,
                          width: 300,
                          decoration: new BoxDecoration(
                              image: new DecorationImage(
                                image: new NetworkImage(videos[index][index]["snippet"]
                                ["thumbnails"]["high"]["url"]),
                                fit: BoxFit.cover,),
                              borderRadius: BorderRadius.circular(10)
                          ),
                          padding: EdgeInsets.all(8.0),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: new Center(child: Text(videos[index][index]["snippet"]["title"], textAlign: TextAlign.center,),),
                        ),
                      ],
                    ),
                  ),
                );
              })
    );
  }

我希望所有视频列表都在播放列表中,但是我只能获得前50个完美的列表。那么,如何从youtube播放列表中获取所有视频?

1 个答案:

答案 0 :(得分:0)

您可以放置​​一个while循环,以检查nextPageToken是否为null,如果不是,则继续获取它并将其保存在临时列表中。完成后,您可以将其保存在原始列表中。

while (pageToken != null) {
  final response = await DataFetcher(
      playlistId: playlistId,
      pageToken: pageToken)
      .FetchVideoFromPlaylist();
  final extracted_data = json.decode(response) as Map<String, dynamic>;
  pageToken = extracted_data['nextPageToken'];
  List<dynamic> data = extracted_data['items'];
  data.forEach((item) {
    title = item['snippet']['title'];
    thumbnail_url = item['snippet']['thumbnails']['high']['url'];
    videoid = item['contentDetails']['videoId'];
    print(title);
    videoDet.add(
        new VideoDetails(
            videoId: videoid,
            videoUrl: null,
            video_thumbnail: thumbnail_url,
            video_title: title)
    );
  });

  if (id == 1)
    cdVideoData = videoDet;}

在此DataFetcher中,该函数用于从youtube提取视频。 videodet是一个临时列表,用于存储视频,直到完成所有添加为止