So basically I am getting data from an api using the http package in flutter. The response.body is an array that looks like this:
[
{
"id":1,
"full_name":"Cristiano Ronaldo",
"avatar":"http://localhost:8000/media/avatars/Ronaldo.jpeg",
"created":"2021-06-30T02:25:56.332816Z"
},
{
"id":2,
"full_name":"Paul Pogba",
"avatar":"http://localhost:8000/media/avatars/Pogba.jpeg",
"created":"2021-06-30T02:49:17.649970Z"
},
{
"id":3,
"full_name":"Paulo Dybala",
"avatar":"http://localhost:8000/media/avatars/Dybala.jpeg",
"created":"2021-06-30T02:52:33.338296Z"
},
{
"id":4,
"full_name":"Leonel Messi",
"avatar":"http://localhost:8000/media/avatars/Messi.jpeg",
"created":"2021-06-30T02:53:39.539556Z"
},
{
"id":5,
"full_name":"Kylian Mbappe",
"avatar":"http://localhost:8000/media/avatars/Mbappe.jpeg",
"created":"2021-06-30T02:57:29.891686Z"
}
]
My problem is I want to essentially format this into the "dart" way. Something like this:
List players = response.body;
The error I'm getting is this:
A value of type 'String' can't be assigned to a variable of type 'List<dynamic>'.
Try changing the type of the variable, or casting the right-hand type to 'List<dynamic>'.
Why is this error occurring. I know the list is already properly formatted and the key-value pairs of the json objects are all strings but I would like to format it into the "dart" way. If I do this:
var players = response.body;
It does work. Should I just use var and call it good or should I format it?
Side Question: If I wanted to call the method to get the data from the api in the initState method, would I do:
Future<void> _getPlayers() async {
...
}
void initState() {
super.initState();
_getPlayers();
}
Thank You!