Michel Feinstein
Michel Feinstein

Reputation: 14296

When to check for mounted before setting state?

The docs here say that:

It is an error to call this method after the framework calls dispose. You can determine whether it is legal to call this method by checking whether the mounted property is true.

I have never seen a Flutter example that checks for the mounted property, so which cases should we bother to actually check it?

Upvotes: 0

Views: 1581

Answers (1)

Saed Nabil
Saed Nabil

Reputation: 6871

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.

quoted from SDK source

Upvotes: 2

Related Questions