I am a beginner in Flutter and I am trying to build a lyrics app using the API from https://rapidapi.com/brianiswu/api/genius/
The problem is I can't seem to access the array called "hits" that is inside an object called "response"
"response": {
"hits": [
{
"highlights": [],
"index": "song",
"type": "song",
"result": {
"annotation_count": 5,
"api_path": "/songs/6419329",
"artist_names": "ROSÉ",
"full_title": "Gone by ROSÉ",
"header_image_thumbnail_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.300x300x1.jpg",
"header_image_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.1000x1000x1.jpg",
"id": 6419329,
"lyrics_owner_id": 10919416,
"lyrics_state": "complete",
"path": "/Rose-gone-lyrics",
"pyongs_count": 258,
"song_art_image_thumbnail_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.300x300x1.jpg",
"song_art_image_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.1000x1000x1.jpg",
"stats": {
"unreviewed_annotations": 0,
"concurrents": 6,
"hot": false,
"pageviews": 1908176
},
"title": "Gone",
"title_with_featured": "Gone",
"url": "https://genius.com/Rose-gone-lyrics",
"primary_artist": {
"api_path": "/artists/1032508",
"header_image_url": "https://images.genius.com/57cb1380a4238e1dcc47fd14c18fc4bc.1000x500x1.jpg",
"id": 1032508,
"image_url": "https://images.genius.com/a88593efb71bc22510f0d1ec46899da5.1000x1000x1.jpg",
"is_meme_verified": false,
"is_verified": false,
"name": "ROSÉ",
"url": "https://genius.com/artists/Rose"
}
}
},
]
}
Using the dio and riverpod package, I tried to implement the following code:
Future<List<Songs>> getData() async {
Dio dio = Dio();
try{
final response = await dio.get('https://genius.p.rapidapi.com/search',
queryParameters: {'q': 'Blackpink'},
options: Options(headers: {
'X-RapidAPI-Host': 'genius.p.rapidapi.com',
'X-RapidAPI-Key': 'bf5ec94953msh94dc7db178f218cp1f29f2jsn7e7fdfb01965'
}));
final data =(response.data['hits'] as List).map((e) => Songs.fromJson(e)).toList();
return data;
} on DioError catch (err) {
print(err);
return [];
}
}
And this is my factory from Json code:
factory Songs.fromJson(Map<String, dynamic> json) {
return Songs(
title: json['title'] ,
url: json['url'] ,
artist: json['artist_names'] ,
imageUrl: json['song_art_image_url'],
);
}
CodePudding user response:
You should first decode your response then access to hits in response. Here is an example query
var jsonResult = json.decode(response.data);
List<Songs> data =(jsonResult["response"]['hits'] as List<dynamic>).map((e) => Songs.fromJson(e)).toList();
CodePudding user response:
First you have to Decode that Raw data then parse to the map:
var rawData=json.decode(response.data);
for(var element in rawData["response"]["hits"]){
Songs songs=Songs.fromJson(element);
}