Search code examples
flutterdartflutter-state

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


I am counting a number of swipes by user and it does count as it gets print in the console but after swiping I get this error:-

  [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().

The function and where error takes me I have commented that and I am not sure if I make any changes in setState then it doesn't keep the counts or remember the count when I switch to home other tab as I want to keep this in memory:-

   _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;
    });
}

Solution

  • When you call setState(), if the associated StatefulWidget is not mounted (i.e. visible on screen), you get this error.

    For synchronous code, this is usually not a problem, but with asynchronous code, you can end up calling setState after the state has been disposed.

    To fix this, find the line that throws the error, and check that the State is mounted before calling setState, e.g.:

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