How to add List of SongInfo from Flutter Audio Query to audio service MediaItem in flutter?

971 Views Asked by At

I tried to look for solutions on internet but I didn't get one. I also tried some ways but still it didn't work. I have used just audio and flutter audio query plugins for audio player, and I tried to use audio service plugin for making it running in background and notification controls. I don't know how to implement the List<SongInfo> to .<MediaItem>

Sample code for Audio Query

List<SongInfo> songs = [];

void getTracks() async {
    songs = await audioQuery.getSongs();
    setState(() {
      songs = songs;
    });
  }

Sample for audio Service:

class AudioPlayer extends BackgroundAudioTask{
  final FlutterAudioQuery audioQuery = FlutterAudioQuery();

  //background audio player class
  final _queue = <MediaItem>[];
}
1

There are 1 best solutions below

0
Ryan Heise On

List.map is perfect for converting a list of one type to a list of another type.

_queue.addAll(songs.map((song) => MediaItem(
      id: song.id,
      album: song.album,
      title: song.title,
    )));

This maps each song into a media item by taking each property value of the song and using it as the appropriate parameter value when constructing the media item. map will do this for each song in the list and produce an iterable of media items which you can either add to your _queue as demonstrated above, or alternatively converted to a list with .toList().