'how to dispose setState properly to avoid memory leak?
It shows me this error.
E/flutter (22343): 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.
E/flutter (22343): 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.
E/flutter (22343): 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().
@override
void initState() {
super.initState();
if(mounted){
getProfilePosts();
getFollowers();
getFollowing();
checkIfFollowing();
}
}
checkIfFollowing() async {
if(mounted){
setState(() {
_isLoading = true;
});
DocumentSnapshot doc = await followersRef
.document(widget.profileId)
.collection('userFollowers')
.document(currentUserId)
.get();
setState(() {
_isFollowing = doc.exists;
});
setState(() {
_isLoading = false;
});
}
}
getFollowers() async {
if(mounted){
setState(() {
_isLoading = true;
});
QuerySnapshot snapshot = await followersRef
.document(widget.profileId)
.collection('userFollowers')
.getDocuments();
setState(() {
followerCount = snapshot.documents.length;
});
setState(() {
_isLoading = false;
});
}
}
getFollowing() async {
if(mounted){
setState(() {
_isLoading = true;
});
QuerySnapshot snapshot = await followingRef
.document(widget.profileId)
.collection('userFollowing')
.getDocuments();
setState(() {
followingCount = snapshot.documents.length;
});
setState(() {
_isLoading = false;
});
}
}
getProfilePosts() async {
if(mounted){
setState(() {
_isLoading = true;
});
QuerySnapshot snapshot = await postsRef
.document(widget.profileId)
.collection('userPosts')
.orderBy('timestamp', descending: true)
.getDocuments();
setState(() {
postCount = snapshot.documents.length;
posts = snapshot.documents.map((doc) => Post.fromDocument(doc)).toList();
_isLoading = false;
});
}
}
Solution 1:[1]
You can override setState to use it only if the State object is mounted on the widget tree.
@override
void setState(fn) {
if (mounted) super.setState(fn);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dinesh Bala |
