【发布时间】:2021-02-24 00:39:30
【问题描述】:
我从 REST api 得到的响应如下所示
{
"result": {
"newsfeed": [
{
"_id": "5fa52495f0e30a0017f4dccf",
"video": null,
"image": null,
"author": [
{
"_id": "5f6a412d2ea9350017bec99f",
"userProfile": {
"visits": 0,
"bio": "Nothing for you ",
"gender": "Male",
"university": "Bells University Of Technology"
},
"name": "Jo Shaw ",
"__v": 0
}
],
"text": "have you seen this ?",
"campus": "Technology",
"isLiked": false
}
]
}
}
我正在使用 FutureBuilder 来处理获取数据,FutureBuilder 返回一个 ListView.builder,我使用它来构建我的布局,具体取决于响应中的项目数
这是我的 UI 的代码
return Scaffold(
body: FutureBuilder<TimelineModel>(
future: _future,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError || snapshot.data == null) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: Column(
children: [
Container(
child: Center(
child: Text("It's empty here"),
),
),
],
),
);
} else {
print("length: " +
snapshot.data.result.newsfeed.length.toString());
return RefreshIndicator(
onRefresh: _getData,
child: ListView(
children: [
ListView.builder(
itemCount: snapshot.data.result.newsfeed.length,
itemBuilder: (context, index) {
return Column(
children: <Widgets>[
//This line of code works properly and no error is gotten
Text( snapshot.data.result.newsfeed[index].text),
//Once I put in this line of code, i receive a range error (RangeError (index): Invalid value: Only valid value is 0: 1)
Text(snapshot.data.result.newsfeed[index].author[index].name),
],
);
}
)
]
)
)
}
}
}
)
);
这是我尝试执行 snapshot.data.result.newsfeed[index].author[index].name 或使用作者数组内对象中的任何项目时看到的错误
【问题讨论】: