search method

Future search(
  1. String query, {
  2. List<SearchType> type = SearchType.values,
  3. String? market,
  4. int offset = 0,
  5. int limit = 20,
})

Performs a search query on Spotify.

  • query: The search query string.
  • type: The types of items to search for (albums, artists, playlists, tracks).
  • market: An optional market (country code) to filter results.
  • offset: The index of the first result to return.
  • limit: The maximum number of results to return.

Returns a list of search results matching the query.

Implementation

Future<dynamic> search(
  String query, {
  List<SearchType> type = SearchType.values,
  String? market,
  int offset = 0,
  int limit = 20,
}) async {
  if (!loggedIn || accessToken == null) {
    throw Exception('User is not logged in or access token is missing.');
  }

  try {
    // Construct query parameters for the search API
    final queryParams = {
      'q': query,
      'type': type.map((e) => e.name).join(','),
      if (market != null) 'market': market,
      'offset': offset,
      'limit': limit,
    };

    // Make an API request to search Spotify
    final response = await _dio.get(
      'https://api.spotify.com/v1/search',
      queryParameters: queryParams,
    );

    // Parse the search results based on their type
    final albums = ((response.data['albums']?['items'] as List?) ?? []).map(
      (e) => SimplifiedAlbum.fromMap(e),
    );
    final artists = ((response.data['artists']?['items'] as List?) ?? []).map(
      (e) => Artist.fromMap(e),
    );
    final playlists =
        ((response.data['playlists']?['items'] as List?) ?? []).map(
      (e) => SimplifiedPlaylist.fromMap(e),
    );
    final tracks = ((response.data['tracks']?['items'] as List?) ?? []).map(
      (e) => TrackModel.fromMap(e),
    );

    // Return all search results as a single list
    return [
      ...albums,
      ...artists,
      ...playlists,
      ...tracks,
    ];
  } catch (e) {
    throw Exception('Error searching Spotify: $e');
  }
}