fetchYoutubeUrls method

Future<List<String>> fetchYoutubeUrls(
  1. BuildContext context,
  2. String apiKey, {
  3. required String query,
})

Fetches a list of YouTube video URLs based on the provided search query.

The function uses the YouTube Data API to search for videos related to the query.

context: The BuildContext used to retrieve localization strings. query: The search query string. Returns a list of YouTube video URLs. Throws an exception if the API request fails.

Implementation

Future<List<String>> fetchYoutubeUrls(BuildContext context, String apiKey,
    {required String query}) async {
  final String endpoint = 'https://www.googleapis.com/youtube/v3/search';

  final Uri url = Uri.parse('$endpoint?key=$apiKey&q=$query&type=video');
  // final Uri url = Uri.parse(
  //     '$endpoint?key=${dotenv.env['YOUTUBE_API_KEY']}&q=$query&type=video');
  try {
    final response = await http.get(url);

    print(response.statusCode);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      List<String> videoUrls = [];

      for (var item in data['items']) {
        String videoId = item['id']['videoId'];
        String videoUrl = 'https://www.youtube.com/watch?v=$videoId';
        videoUrls.add(videoUrl);
      }

      return videoUrls;
    } else {
      // throw Exception('Failed to load YouTube URLs');
      // throw Exception(
      //     AppLocalizations.of(context)!.aiGenerationAPIGemma_errorFetchYoutube);
      return [];
    }
  } catch (e) {
    return [];
    // throw Exception(
    //     AppLocalizations.of(context)!.aiGenerationAPIGemma_errorFetchYoutube);
  }
}