getTopTracks method

Future<List<Track>> getTopTracks({
  1. required String user,
  2. Period? period,
  3. int page = 1,
  4. int limit = 50,
})

Get the top tracks listened to by a user. You can stipulate a time period. Sends the overall chart by default.

NOTE: the output list is already ordered by rank.

https://www.last.fm/api/show/user.getTopTracks

Implementation

Future<List<Track>> getTopTracks({
  required String user,
  Period? period,
  int page = 1,
  int limit = 50,
}) async {
  final parameters = {
    'user': user,
    'period': period?.value,
    'page': page,
    'limit': limit,
  };

  // TODO: is the rank necessary!?

  final request = Request(
    api: _api,
    method: 'user.getTopTracks',
    parameters: parameters,
  );

  final response = await request.send(mode: RequestMode.GET);

  final topTracks = response['toptracks']['track'];

  if (topTracks == null) {
    return [];
  } else {
    // This operation is necessary because the tracks have different duration.
    var fixTopTracks = List.generate(
      (topTracks as List).length,
      (i) => Track.fromJson(topTracks[i]),
    );

    for (var track in fixTopTracks) {
      if (track.duration != null) {
        track.duration = track.duration! * 1000;
      }
    }
    return fixTopTracks;
  }
}