Home > Enterprise >  Flutter audio_service add item from json
Flutter audio_service add item from json

Time:03-11

audio_service new update removed fromjson in model class .. how can i add media item from json? My json look like this

 [
{
    "id": "http://581.22.00.66:8500/1?type=http",
    "title": "test",
    "artist": "test",
    "album": "test",
    "artUri": "test.png",
    "genre": "8535",
    "displayDescription": "23"
},
{
    "id": "http://581.22.00.66:6600/2?type=http",
    "title": "test2",
    "artist": "test2",
    "album": "test2",
    "artUri": "test2.png",
    "genre": "1498",
    "displayDescription": "23"
},

we using dio for json.

List<MediaItem> _queue = [];
void getdata() async {
  final response = await Dio().get(Constants.url 'post.php', queryParameters: {
  });
  for (int i = 0; i < response.data.length; i  ) {
    _queue.add(response.data[i]);
  }
}

Error:

 Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'MediaItem'

CodePudding user response:

If there is no default method to do that, you can create a JSON(map) parser function to audio_service's Media model.

Note: parser function converts only the fields that you provide on your json data.

MediaItem jsonToMeidaItem(Map data) {
  return MediaItem(
          id: data['id'].toString(),
          title: data['title'].toString(),
          artist: data['artist'].toString(),
          album: data['album'].toString(),
          artUri: data['artUri'].toString(),
          genre: data['genre'].toString(),
          displayDescription: data['displayDescription'].toString(),
  );
}

Then you could be able to convert JSON data to MediaItem.

Substituted converter-function to your code:

List<MediaItem> _queue = [];
void getdata() async {
  final response = await Dio().get(Constants.url 'post.php', queryParameters: {
  });
  for (int i = 0; i < response.data.length; i  ) {
     final MediaItem mediaItem = jsonToMeidaItem(response.data[i]);
    _queue.add(mediaItem);
  }
}
  • Related