【发布时间】:2021-10-23 15:08:14
【问题描述】:
我正在从我的 API 获取一些数据。我通过将返回的 JSON 转换为一些小部件 CommentaireSingle 来处理它们。
但是对于我来说,关于 build 方法,我有一些不清楚的地方。
- 每次构建小部件时都会调用 build,包括
setState方法。 - FutureBuilder 用于在内容完全加载后生成内容。
- ValueChanged 用于将数据从子级传递给其父级。
所以我的问题是:为什么每次我执行setState,我的Future 都会将原始数据添加到我的视图中?我必须清除最初的 listCommentsWidgets 是为了获得“逻辑”结果(没有两倍于原始小部件列表)
class _CommentairesListingState extends State<CommentairesListing> {
List<Commentaire> listComments = [];
Future loadListComments;
List<Widget> listCommentsWidgets = [];
@override
void initState() {
super.initState();
loadListComments = _loadComments();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: loadListComments,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return generateComments();
} else {
return Center(
child: SizedBox(
height: 25,
width: 25,
child: CircularProgressIndicator(),
),
);
}
},
);
}
Future _loadComments() async {
listComments = await MyWS()
.getComs(widget.publication.pubId);
}
Expanded generateComments() {
listCommentsWidgets.clear();
for (Commentaire commentaire in listComments) {
CommentaireSingle single = CommentaireSingle(
...
toRemove: updateCommentaireListing, #ValueChanged
responseTo: widget.responseTo);
listCommentsWidgets.add(single);
}
Column column = Column(
children: listCommentsWidgets,
);
return Expanded(
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.90,
child: SingleChildScrollView(
child: column,
),
),
),
);
}
void updateCommentaireListing(Commentaire commentaire) {
setState(() {
listComments.remove(commentaire);
listCommentsWidgets.clear();
});
}
}
【问题讨论】:
标签: flutter future setstate flutter-futurebuilder