Lập chỉ mục trong Listview.builder
Phản hồi tôi nhận được từ api REST của mình trông như thế này
{
"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
}
]
}
}
Tôi đang sử dụng FutureBuilder để xử lý việc tìm nạp dữ liệu và FutureBuilder trả về một ListView.builder mà tôi sử dụng để xây dựng bố cục của mình tùy thuộc vào số lượng mục trong phản hồi
Đây là mã cho giao diện người dùng của tôi
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),
],
);
}
)
]
)
)
}
}
}
)
);
Đây là lỗi gặp phải khi tôi cố gắng thực hiện snapshot.data.result.newsfeed [index] .author [index] .name hoặc sử dụng bất kỳ mục nào trong đối tượng bên trong mảng tác giả
Trả lời
Như @xion đã đề cập, bạn đang sử dụng newsfeedchỉ mục cho authormảng. Những gì bạn nên làm là gán tất cả các tác giả trong mỗi newsfeedmục thành chuỗi và sau đó sử dụng giá trị đó thay thế. Dưới đây là mã để cung cấp cho bạn ý tưởng về những gì bạn nên làm. Vì tôi không có quyền truy cập vào API của bạn nên tôi đã mã hóa cứng phản hồi json của bạn.
class MyApp extends StatefulWidget {
MyApp({Key key, this.title}) : super(key: key);
final String title;
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
var testJson = json.decode('''
{
"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
},
{
"_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
}
]
}
}
''');
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(children: [
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: testJson["result"]["newsfeed"].length,
itemBuilder: (context, index) {
String authors = '';
List<dynamic> authorsArray = testJson["result"]["newsfeed"][index]["author"];
for (int i = 0; i < authorsArray.length; i++) {
authors += i == (authorsArray.length - 1) ? authorsArray[i]["name"].toString() : authorsArray[i]["name"].toString() + ", ";
}
return Column(
children: [
Padding(
padding: EdgeInsets.all(10.0),
child: Text(
"Title: " +
testJson["result"]["newsfeed"][index]["text"],
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0),
),
),
Text("Authors: " + authors,
style: TextStyle(
color: Colors.black54,
fontStyle: FontStyle.italic)),
],
);
}),
]),
),
),
);
}
}
Ảnh chụp màn hình:
tác giả của bạn đang truy cập cùng một chỉ mục với nguồn cấp tin tức của bạn
có lẽ bạn nên cần một vòng lặp khác cho tác giả của bạn
ListView.builder(
itemCount: snapshot.data.result.newsfeed.length,
itemBuilder: (context, index) {
return Column(
children: <Widgets>[
Text( snapshot.data.result.newsfeed[index].text),
Text(snapshot.data.result.newsfeed[index].author[index].name), // <--- this line author[Index] hits error, not news the newsfeed
],
);
}
)