getAllSongs method

Future<List<Artist>> getAllSongs({
  1. bool sort = false,
  2. int coverArtSize = 500,
})

Fetch all songs in the Apple Music library.

This method may take up significant time due to the amount of songs available on the phone.

All cover art for each album is fetched when using this function. Due the amount of songs, the app may crash if the device does not have enough memory. In this case, the coverArtSize should be reduced.

sort can be set to true in order to sort the artists alphabetically.

Implementation

Future<List<Artist>> getAllSongs(
    {bool sort = false, int coverArtSize = 500}) async {
  final artists = <Artist>[];
  final result = await playerChannel
      .invokeMethod('getAllSongs', <String, dynamic>{'size': coverArtSize});
  for (var a = 0; a < result.length; a++) {
    final resobj = Map<String, dynamic>.from(result[a]);
    final artist = Artist(albums: [], name: resobj['artist']);
    Uint8List? image;
    if (Platform.isIOS) {
      if (resobj['image'] != null) {
        image = Uint8List.fromList(List<int>.from(resobj['image']));
      }
    } else if (Platform.isAndroid) {
      final String? imageFilePath = resobj['imagePath'];
      if (imageFilePath != null) {
        final imageFile = File(imageFilePath);
        if (await imageFile.exists()) {
          image = await imageFile.readAsBytes();
        }
      }
    }
    final album = Album(
        songs: [],
        title: resobj['albumTitle'],
        albumTrackCount: resobj['albumTrackCount'] ?? 0,
        coverArt: image,
        discCount: resobj['discCount'] ?? 0,
        artistName: artist.name);
    final song = Song.fromJson(resobj);
    album.songs.add(song);
    artist.albums.add(album);
    album.artistName = artist.name;
    var foundArtist = false;
    for (var i = 0; i < artists.length; i++) {
      if (artist.name == artists[i].name) {
        foundArtist = true;
        var foundAlbum = false;
        for (var j = 0; j < artists[i].albums.length; j++) {
          if (artists[i].albums[j].title == album.title) {
            //If the album does not have a cover art
            if ((artists[i].albums[j].coverArt == null &&
                    album.coverArt != null) ||
                (artists[i].name != album.artistName)) {
              album.coverArt = artists[i].albums[j].coverArt = album.coverArt;
            }
            artists[i].albums[j].songs.add(song);
            artists[i]
                .albums[j]
                .songs
                .sort((a, b) => a.trackNumber - b.trackNumber);
            foundAlbum = true;
            break;
          }
        }
        if (!foundAlbum) {
          artists[i].albums.add(album);
          artists[i].albums.sort((a, b) => a.title.compareTo(b.title));
        }
      }
    }
    if (!foundArtist) {
      artists.add(artist);
    }
  }
  if (sort) artists.sort((a, b) => a.name.compareTo(b.name));
  return artists;
}