我正在嘗試在 ListView 中列出我的所有評論。他們有父子關系,我想從方法中展示他們,當按下按鈕以顯示子評論時,該方法會遞回呼叫自身。
listViewComments(List<Comments>? comments) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: comments!.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 4),
child: Card(
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
getPictureOfUser(comments[index].userId),
headers: tokenWithHeader),
),
title: SizedBox(
width: 300,
child: Text(
"${comments[index].userFirstName} ${comments[index].userLastName}"),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(comments[index].text),
Row(
children: [
TextButton(
onPressed: () {},
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: const [
Icon(Icons.reply),
Text(
'REPLY',
style: TextStyle(
fontSize: 9.0,
),
),
]),
),
if (comments[index].childComments.isNotEmpty)
TextButton(
onPressed: () {
listViewComments(comments[index].childComments);
},
child: Text( //show if there's child comment
'SHOW (${comments[index].childComments.length})',
style: const TextStyle(
fontSize: 9.0,
),
),
),
],
),
],
),
),
),
);
},
);
}
當我執行此代碼時,沒有任何反應。為什么會這樣,有沒有更好的方法來做到這一點?
uj5u.com熱心網友回復:
您需要一個狀態來顯示/隱藏評論。為此,您可以提取StatefulWidget具有此狀態的 a 或
listViewComments(List<Comments>? comments) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: comments!.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 4),
child: Builder(builder: (context) {
var showChildComments = false;
return StatefulBuilder(builder: (context, setState) {
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
getPictureOfUser(comments[index].userId),
headers: tokenWithHeader),
),
title: SizedBox(
width: 300,
child: Text(
"${comments[index].userFirstName} ${comments[index].userLastName}"),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(comments[index].text),
Row(
children: [
TextButton(
onPressed: () {},
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: const [
Icon(Icons.reply),
Text(
'REPLY',
style: TextStyle(
fontSize: 9.0,
),
),
]),
),
if (comments[index].childComments.isNotEmpty)
TextButton(
onPressed: () {
//listViewComments(comments[index].childComments);
setState(
() => showChildComments = !showChildComments,
);
},
child: Text(
//show if there's child comment
'${showChildComments ? 'HIDE' : 'SHOW'} (${comments[index].childComments.length})',
style: const TextStyle(
fontSize: 9.0,
),
),
),
],
),
if (showChildComments)
listViewComments(comments[index].childComments),
],
),
),
);
});
}),
);
},
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507855.html
