微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我刷卡时出现此错误:-Unhandled Exception: setState() 在 dispose() 之后调用

如何解决当我刷卡时出现此错误:-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(() {
        
      });
    
    });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。