getAllSongs method

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

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. Make sure to display a waiting animation while this is fetching. All cover art 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 size of the cover art should be reduced.

Implementation

Future<List<Artist>> getAllSongs({bool sort = false, int coverArtSize = 50}) async {
  if(Platform.isIOS){
    try{
      List<Artist> artists = [];
      var result = await playerChannel.invokeMethod('getAllSongs', <String, dynamic>{
        "size": coverArtSize
      });
    // print(result[0]);
      for(int a=0; a<result.length; a++) {
        stdout.write(a.toString() + ", ");
        var resobj = new Map<String, dynamic>.from(result[a]);
        Artist artist = Artist(albums: [], name: resobj["artist"]);
        Image image = resobj["image"] != null ? Image.memory(resobj["image"]) : null;
        Album album = Album(songs: [], title: resobj["albumTitle"], albumTrackCount: resobj["albumTrackCount"], coverArt: image, diskCount: resobj["diskCount"], artistName: artist.name);
        Song song = Song(albumTitle: album.title, title: resobj["songTitle"], trackNumber: resobj["albumTrackNumber"], discNumber: resobj["discNumber"], isExplicit: resobj["isExplicitItem"], playCount: resobj["playCount"], iOSSongID: resobj["songID"].toString(), artistName: artist.name);
        album.songs.add(song);
        artist.albums.add(album);
        album.artistName = artist.name;
        bool foundArtist = false;
        for(int i=0; i<artists.length; i++){
          if(artist.name == artists[i].name){
            foundArtist = true;
            bool foundAlbum = false;
            for(int j=0; j<artists[i].albums.length; j++){
              if(artists[i].albums[j].title == album.title){
                artists[i].albums[j].songs.add(song);
                print("sorted");
                artists[i].albums[j].songs.sort((a, b) => a.trackNumber - b.trackNumber);
                foundAlbum = true;
                break;
              }
            }
            if(!foundAlbum){
              artists[i].albums.add(album);
            }
          }
        }
        if(!foundArtist){
          artists.add(artist);
        }
      }
      if(sort)
        artists.sort((a, b) => a.name.compareTo(b.name));
      return artists;
    } catch(e){
      print(e);
      return [];
    }
  }
}