When I swipe gets this error:-Unhandled Exception: setState() called after dispose()

When I swipe gets this error:-Unhandled Exception: setState() called after dispose()

我正在计算用户的滑动次数,当它在控制台中打印时它确实计数但是在滑动之后我得到这个错误:-

  [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: setState() called after dispose(): _HomeState#990d2(lifecycle state: defunct, not mounted, ticker inactive)
  This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
  The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
  This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().

功能和错误带我去哪里 我已经评论过,我不确定我是否在 setState 中进行了任何更改,然后它不会保留计数或在我根据需要切换到其他选项卡时记住计数将其保存在内存中:-

   _getCurrentUser() async {
  User user =  await auth.currentUser;

return docRef

    .doc("${user.uid}")
    .snapshots().listen((data) async {
  currentUser = CreateAccountData.fromDocument(data);
  if (mounted) setState(() {});
  users.clear();
  userRemoved.clear();
  getUserList();
   getLikedByList();
  _getSwipedcount();

  // configurePushNotification(currentUser);
  return currentUser;
});
 }


int swipecount = 0;

_getSwipedcount() {
  FirebaseFirestore.instance.collection('/users/${currentUser.uid}/CheckedUser')
    .where(
      'timestamp',
      isGreaterThan: Timestamp.now().toDate().subtract(Duration(days: 1)),
    )
    .snapshots()
    .listen((event) {
      print("swipe "+event.docs.length.toString());
      setState(() {     ///Error takes me here to the setState
        swipecount = event.docs.length;
      });
      return event.docs.length;
    });
}

当您调用 setState() 时,如果关联的 StatefulWidget 未安装(即在屏幕上可见),您将收到此错误。

对于同步代码,这通常不是问题,但对于异步代码,您可以在处理完状态后调用 setState

要解决此问题,请找到引发错误的行,并在调用 setState 之前检查 State 是否已挂载,例如:

if (mounted) {
  setState(() {
    // update UI
});
}

添加延迟将解决此问题。

  Future.delayed(const Duration(milliseconds: 500), () {
    
      setState(() {
        
      });
    
    });