getQuerySuggestions method

Future<List<String>> getQuerySuggestions(
  1. String query
)

Returns the suggestions youtube provide while search on the page.

Implementation

Future<List<String>> getQuerySuggestions(String query) async {
  final request = await _httpClient.get(
    Uri.parse(
      'https://suggestqueries-clients6.youtube.com/complete/search?client=youtube&hl=en&gl=en&q=${Uri.encodeComponent(query)}&callback=func',
    ),
  );
  final body = request.body;
  final startIndex = body.indexOf('func(');
  final jsonStr = body.substring(startIndex + 5, body.length - 1);
  final data = json.decode(jsonStr) as List<dynamic>;
  final suggestions = data[1] as List<dynamic>;
  return suggestions.map((e) => e[0]).toList().cast<String>();
}