Home > Back-end >  Is it Good practice to use mounted in all the place whenever calling setState in flutter app?
Is it Good practice to use mounted in all the place whenever calling setState in flutter app?

Time:03-29

I have used setState correctly in all the places of my application. But in rare case, sometimes this error(Image Attached) is coming. So is it Good to use mounted condition in all the places of the application with setState?

I have two questions kindly share your knowledge.

  1. If i use mounted in all the places of the application then my app performance will get affected?
  2. Why Flutter team is not used mounted inside the setState?

enter image description here

CodePudding user response:

  1. You don't need to use mounted everywhere - Just use it in places where you're calling setState from within some sort of asynchronous callback. Performance shouldn't be affected - it's a simple boolean check.

  2. It wouldn't necessarily be beneficial for setState to check mounted for you. For example, say you would like to persist some data from a REST API call, then render the data. You might always want to persist the data, but you would only want to re-render if the widget is mounted. If you put both of those operations within a setState call, then your data wouldn't be persisted, but you wouldn't know, because setState would quietly omit the operation.

Disclaimer: I'm not advocating calling REST APIs or persisting data directly from your widgets - This is just an example where getting an exception is better than having the SDK simply not run your code.

CodePudding user response:

Using mounted is not mandatory, but it’s a good practice. So first of all, let’s see when does the error occur. Let’s suppose you are fetching a data in background and the user is allowed to interact with the app until the data is fetched (in other words, background fetch kind of thing) and once the data is fetched, you are using setState. Now, let’s suppose that your data fetch took around 2 seconds and before that user navigated to some other page. So in this case, your widget on which you were going to perform setState is no longer available in the widget tree because user already navigated to any other page.

Hence, it’s a good practice to use mounted whenever you use setState as well as when you are performing some operations which includes the use of context because even the context can get changed or updated.

Also, this doesn’t affect your app performance as it’s simply a condition which checks whether the current widget is present in the widget tree or not.

I hope this solves your confusion.

  • Related