当我刷卡时出现此错误:-Unhandled Exception: setState() 在 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

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

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

添加一个延迟就可以解决这个问题。

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