【发布时间】:2021-06-30 06:24:30
【问题描述】:
所以基本上我是在 Flutter 中使用 http 包从 api 获取数据。 response.body 是一个如下所示的数组:
[
{
"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"
}
]
我的问题是我想基本上将其格式化为“飞镖”方式。像这样的:
List players = response.body;
我得到的错误是这样的:
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>'.
为什么会出现这个错误。我知道列表已经正确格式化,并且 json 对象的键值对都是字符串,但我想将其格式化为“飞镖”方式。如果我这样做:
var players = response.body;
确实有效。我应该只使用 var 并称之为好还是应该格式化它?
附加问题: 如果我想在initState方法中调用方法从api获取数据,我会这样做吗:
Future<void> _getPlayers() async {
...
}
void initState() {
super.initState();
_getPlayers();
}
谢谢!
【问题讨论】: