How to use youtube api to call two or more YouTube account at a time using flutter

Viewed 44

Weeks now I have being struggling with this logic. it's an app that uses YouTube api.I am able call the api to display the information of a channel account by using the channel Id I populated in the database. Hence,only one is displaying but I want it to request for a quite a number of them not specific number but I should be able to add up more than one, so different channel account, please ask how can I go about this in flutter?.

This the Home Screen which supposed to display the channels requested.

class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key);

_HomeScreenState createState() => _HomeScreenState(); }

class _HomeScreenState extends State<HomeScreen> {
  ChannelInfo _channelInfo = ChannelInfo();
  VideosList _videosList = VideosList();
  ScrollController? _scrollController;
  Item _item = Item();
  bool _isloading = true;
  final String _playtlistidd = "";
  String _nextTokenPage = "";
  List<String> _channelIdlistcollector = [];
  //UserInformation _information = UserInformation();
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();
  List<String> dataList2 = ["UCsNrLT-M03lvshUuilSJ8XA","UComQiXI7rnjwVU8b6x5epGw","UCC74vXYtWuqDlkoLy6XfcHQ"];
  @override
  void initState() {
    super.initState();
    _isloading = true;
    _scrollController = ScrollController();
    _videosList.videos = [];

    _getchannel();
  }

  _getchannel() async {
    //_channelIdlistcollector = (await _information.getDataFromFirebase()) as List<String>;
    // problem identified here

    _channelInfo = (await API_Service.instance.fetchChannelDetails(dataList2,));

    _item = _channelInfo.items![0];
    //print(_item.snippet);

    setState(() {
      _isloading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    final user = FirebaseAuth.instance.currentUser;
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      body: _isloading
          ? Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.all(5),
                    child: Column(
                      children: [
                        //Insert Username here
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "Hi User",
                            style: TextStyle(
                                fontSize: 30, fontWeight: FontWeight.bold),
                          ),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        Text(
                          "Categories",
                          textAlign: TextAlign.left,
                          style: TextStyle(fontSize: 25),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            CategoryButton("Basic 1"),
                            CategoryButton("Basic 2"),
                            CategoryButton("Basic 3")
                          ],
                        ),
                        SizedBox(
                            height: MediaQuery.of(context).size.height / 6.5,
                            child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount: dataList2.length,
                                itemBuilder: (context, index) {
                                  return CategoryCardItem(
                                      "Mathematics",
                                        _item.snippet!.title ?? "",
                                      40.00,
                                      "Basic 3",
                                      _item.snippet!.thumbnails!.high!.url ??
                                          "");
                                })),
                        SizedBox(
                          height: 25,
                        ),
                        Text(
                          "Popular Subjects",
                          style: TextStyle(
                              fontSize: 25, fontWeight: FontWeight.bold),
                        ),
                        GridView(
                          shrinkWrap: true,
                          physics: ScrollPhysics(),
                          padding: EdgeInsets.all(5),
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 2),
                          children: [
                            PopularCourseCard(
                                courseTitle: "English Language",
                                coursePrice: 35,
                                courseClass: "Basic 3",
                                imgLocation:
                                    "lib/assets/images/english_img.jpg"),
                            PopularCourseCard(
                                courseTitle: "English Language",
                                coursePrice: 35,
                                courseClass: "Basic 3",
                                imgLocation:
                                    "lib/assets/images/english_img.jpg"),
                            PopularCourseCard(
                                courseTitle: "English Language",
                                coursePrice: 35,
                                courseClass: "Basic 3",
                                imgLocation:
                                    "lib/assets/images/english_img.jpg"),
                            PopularCourseCard(
                                courseTitle: "English Language",
                                coursePrice: 35,
                                courseClass: "Basic 3",
                                imgLocation:
                                    "lib/assets/images/english_img.jpg"),
                          ],
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}

class CategoryButton extends StatelessWidget {
  final String btnText;

  CategoryButton(@required this.btnText);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ButtonStyle(
          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
              RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(18.0),
        //side: BorderSide(color: Colors.red)
      ))),
      onPressed: () {},
      child: Text(btnText),
    );
  }
}

This is calling the Youtube Api.

class API_Service {
  static const _baseUrl = "www.googleapis.com";
  
  API_Service._instantiate();

  static final API_Service instance = API_Service._instantiate();
  Stream _usersStream =
      FirebaseFirestore.instance.collection("users").snapshots();
  // get the channelId from the database
//Future <dynamic> getDataFromFirebase(){
  //UComQiXI7rnjwVU8b6x5epGw
  // ignore: prefer_typing_uninitialized_variables
  var channelInfo;
//}
  //take a list of the item
  // loop through the item to get
// Uri  ?uri;
  //Map<String,String>? headers;
  //supposed to return a list at this place

  Future  <ChannelInfo> fetchChannelDetails(List<String> list) async {
    for (int i = 0; i < list.length; i++) {
      Map<String, dynamic> parameters = {
        'part': 'snippet,contentDetails,statistics',
        'id': list[i],
        'key': API_KEY,
      };
      Uri uri = Uri.https(_baseUrl, '/youtube/v3/channels', parameters);
      Map<String, String> headers = {
        HttpHeaders.contentTypeHeader: 'application/json',
      };
      // get the Channnel.
      Response response = await http.get(uri, headers: headers);
      print(response.body);
      channelInfo = channelInfoFromJson(response.body);
      //return channelInfo;
    
    }
  return channelInfo;
  }

  Future<VideosList> fetchVideosFromPlaylist(
      {String? playlistId, String? nextpageTT}) async {
    Map<String, String> parameters = {
      'part': 'snippet',
      'playlistId': playlistId!,
      'maxResults': '8',
      'pageToken': nextpageTT!,
      'key': API_KEY
    };
    Uri uri = Uri.https(_baseUrl, '/youtube/v3/playlistItems', parameters);
    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: 'application/json',
    };

    Response response = await http.get(uri, headers: headers);
    print(response.body);
//print(data)
    VideosList videosList = videosListFromJson(response.body);
    return videosList;
  }
}
0 Answers
Related