Importance of Calling SetState inside initState

前端 未结 2 1279
忘了有多久
忘了有多久 2020-11-30 08:06

Should setState() method be called inside initState() method of a StatefullWidget?

My understanding is that initState()<

相关标签:
2条回答
  • 2020-11-30 08:36

    You don't need to use setState within initState. In fact, it will not work if you do so.

    The thing is, you are not calling setState within initState in your example.

    What you do is calling setState on an asynchronous event. But since it's asynchronous, the initState method has already finished

    0 讨论(0)
  • 2020-11-30 08:43

    The setState() method notifies the framework that the internal state of the Stateful widget has changed. Calling this method is what triggers the widget to rebuild with the latest state values, so it is not necessary to call it inside the initState() lifecycle method since it is only called once when the widget is inserted into the widget tree (i.e. when the widget is initialized).

    You can read more about the setState() method here: setState method

    As for the initState() lifecycle method, whenever you override this method you MUST call super.initState(); at the start or end of your method, otherwise, you'll encounter some problems with your widget. Problems like the widget not being inserted into the widget tree.

    The only time you can use setState() inside initState() is within a callback function as you did in the second code snippet. It works because, by the time the callback is run, the widget has already been initialized and inserted into the widget tree and the internal state needs to be updated to trigger a rebuild.

    Also, just take note that setState() will only work if the widget is mounted. For this reason, every widget has a bool this.mounted property which you can check in case you're not certain if the widget will still be mounted when setState() is called. Calling it when the widget is not mounted might crash your app. So I'd advice against calling setState() outside the widget class.

    0 讨论(0)
提交回复
热议问题