Mariam Younes
Mariam Younes

Reputation: 389

Flutter: display YouTube videos from API provider

I'm using the API with provider for fetching data from database, and I have a list of YouTube video links that I want to use for presenting the videos. But I can't put the list of links in _controllers because of the error:

The instance member 'serviceProvider' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression.

This is my code:

static List<YoutubePlayerController> _controllers =
   ['uEZAT3YJvDw', 'zMPfxQunIRw', 'uEZAT3YJvDw'] //I want to replace this line with the api list of links
          .map<YoutubePlayerController>(
            (videoId) => YoutubePlayerController(
              initialVideoId: videoId,
              flags: const YoutubePlayerFlags(
                autoPlay: false,
              ),
            ),
          )
          .toList();

ListView.separated(
                            scrollDirection: Axis.horizontal,
                            shrinkWrap: true,
                        itemBuilder: (context, index) {
                          return Card(
                            child: YoutubePlayer(
                              key: ObjectKey(_controllers[index]),
                              controller: _controllers[index],
                              actionsPadding: const EdgeInsets.only(left: 16.0),
                              bottomActions: [
                                CurrentPosition(),
                                ProgressBar(isExpanded: true),
                                const SizedBox(width: 10.0),
                                RemainingDuration(),
                                FullScreenButton(),
                              ],
                            ),
                          );
                        },
                        itemCount: _controllers.length,
                      )

class HomeDatum {
  HomeDatum({
    this.attachment,
  });
  var attachment; // this json carry the link

  factory HomeDatum.fromJson(Map<String, dynamic> json) => HomeDatum(
        attachment: json["attachment"],
      );}

Future<dynamic> getVideosList() async {

    http.Response response = await http
        .get(url, headers: headers);

    Map<dynamic, dynamic> responseData = json.decode(response.body);
    var results;
    if (responseData['status'] == 1) {
      _homeDatum = [];
      responseData['data'].forEach((element) {
        _homeDatum.add(HomeDatum.fromJson(element));
      });
      results = true;
    } 
    _isLoading = false;
    notifyListeners();
    return results;
  }

Upvotes: 0

Views: 1320

Answers (1)

Shubham Narkhede
Shubham Narkhede

Reputation: 2130

If you are calling API and you want to get data from API and show data on same page. First you need to initialize the

  final List _controllers = [];   // This for your video id's
  static List<YoutubePlayerController> _controllersYoutube; // this is your YouTube Controller data
  var videoData; // This for store API response

Then you need to create API call method and set your id's to _controllersYoutube

  Future getVideos() async {
    var url = "$baseUrl/api/videos";  // Your API
    var response = await http.get(url);
    videoData = json.decode(response.body);
    if (this.mounted) {
      setState(() {
        for (var myAllData in videoData) {
          _controllers.add(myAllData['youtube_video_id']);
        }
        _controllersYoutube = _controllers.map<YoutubePlayerController>((videoId) {

         `// eodZS9Wkab0  yc9JIvamDm4  9Ty_qqvhiI4  Te862nM7mJ0 I'm getting this id's from API`

          return YoutubePlayerController(
            initialVideoId: videoId,
            flags: const YoutubePlayerFlags(
              autoPlay: false,
            ),
          );
        }).toList();
        // loading = false;
      });
    }
  }

And then simply create a UI for show listview with YouTube videos like below

     body: ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemBuilder: (context, index) {
          return Container(
            height: 150,
            child: YoutubePlayer(
              key: ObjectKey(_controllersYoutube[index]),
              controller: _controllersYoutube[index],
              actionsPadding: const EdgeInsets.only(left: 16.0),
              bottomActions: [
                CurrentPosition(),
                ProgressBar(isExpanded: true),
                const SizedBox(width: 10.0),
                RemainingDuration(),
                FullScreenButton(),
              ],
            ),
          );
        },
        itemCount: _controllers.length,
      )

I hope this answer will work for you.

Upvotes: 2

Related Questions