我有一个流构建器正在监听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方法,或者使用您的init方法将流移到构建上下文之外,或者使用提供者在服务文件中进行调用,都是我的设置方法。让我知道你是否正确。

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

10-11 14:56