0

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'
Nagaraj
  • 87
  • 1
  • 8

1 Answers1

1

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);
  }
}
theiskaa
  • 1,202
  • 5
  • 25
  • I try to add it but it show :"The argument type 'String?' can't be assigned to the parameter type 'String'." also null check error – Nagaraj Mar 11 '22 at 10:36
  • Okay, I updated the function script. And put appropriate nullability signs on fields. – theiskaa Mar 11 '22 at 10:38
  • now also same error argument type 'dynamic' can't be assigned to the parameter type 'String'. also add null check – Nagaraj Mar 11 '22 at 10:42
  • I aaded tostring then its work "title: data['title'].toString(). thank you – Nagaraj Mar 11 '22 at 11:00