我有一个收听 Firestore 的流生成器,它有点工作。主要问题是流构建器不断重建(如果它不花费我额外的阅读费用,那么不用担心,但如果确实如此,那么这是一个我假设它确实存在的问题)。当主页面第一次构建时,当我转到另一个页面时,它再次构建,当我弹回主页面时,它第三次重新构建。
代码:
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