gpt4 book ai didi

firebase - Flutter Streambuilder 不断重建

转载 作者:行者123 更新时间:2023-12-02 11:20:40 26 4
gpt4 key购买 nike

我有一个流构建器在监听 Firestore,它有点工作。主要问题是streambuilder不断重建(如果它不花费我额外的读取,那么不用担心,但如果它这样做了,那么这是一个我假设它确实存在的问题)。当主页第一次构建时,当我转到另一个页面时,它会再次构建,当我弹回主页时,它会第三次重建。

代码:

class _RequestsListState extends State<RequestsList> with AutomaticKeepAliveClientMixin {
final Map<String, List<Post>> posts = {};
final List<String> postsUserIDs = [];

@override
bool get wantKeepAlive => true;

@override
Widget build(BuildContext context) {
super.build(context);

print('RequestsList');
User cUser = InheritedUser.of(context).user;

return StreamBuilder<List<Post>>(
initialData: cUser.posts,
stream: APIs().posts.auPostsStream(cUserID: cUser.userID),
builder: (context, snap) {
if (snap.hasError) {
print('AUPostsList.dart StreamBuilder Error: ${snap.error}');
return null;
} else {

print('POSTS LENGTH');
print(snap.connectionState);
print(cUser.posts.length);

this.posts.clear();
this.postsUserIDs.clear();

snap.data.forEach((post) {
if (this.posts[post.user.documentID] == null) {
this.posts[post.user.documentID] = [post];
} else {
this.posts[post.user.documentID].add(post);
}

if (!this.postsUserIDs.contains(post.user.documentID)) {
this.postsUserIDs.add(post.user.documentID);
}
});

return ListView.separated(
controller: widget.scrollController,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.only(top: 0.0),
itemBuilder: (context, index) => RequestItem(posts: this.posts[this.postsUserIDs[index]]),
separatorBuilder: (context, index) => Container(),
itemCount: this.postsUserIDs.length);
}
});
}
}

其次,当我转到第二页时,数组被清空。我没有在任何地方清除它,所以我不确定为什么它在点击一个项目后清空数组......

日志:
Reloaded 0 of 773 
libraries in 169ms.
flutter: ChatsList
flutter: RequestsList
flutter: POSTS LENGTH
flutter: ConnectionState.waiting
flutter: 1
flutter: RequestsList
flutter: POSTS LENGTH
flutter: ConnectionState.waiting
flutter: 0
flutter: ChatsList
flutter: RequestsList
flutter: POSTS LENGTH
flutter: ConnectionState.waiting
flutter: 0
flutter: ChatsList

最佳答案

我知道这已经很晚了,但是使用您的 init 方法或使用提供程序在服务文件中进行调用将流移到构建上下文之外是我进行设置的方式。如果你来对了,请告诉我。

关于firebase - Flutter Streambuilder 不断重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57667577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com