setState() within initState() in dart

If you are using dart, you may have come across instances where setState() is used within initState(), and also instances wherein variables are assigned within initState() without being wrapped around setState(). So, which is the correct implementation? To answer that we need to understand the meaning of setState() and initState().


initState() method is called once when a Stateful widget is inserted in the widget tree. ‘Once’ is the keyword here. It is called before the first build of the widget. To get a more detailed understanding of this, refer to this article explaining the lifecycle of a Stateful widget in flutter. All the variables that require initialization for build should be initialized here.


setState() method notifies the framework that the state has changed, and the widget should be rebuilt. Therefore, whenever the setState() method is called, the framework schedules a build of the widget.

setState within initState

Now, since initState() is called before the first build, calling setState() within initState ideally doesn’t make sense. This is because a build is already scheduled (the first build will soon follow the initState() method), and any variable changes done in initState will reflect in that build.

However, there is one scenario where you need to call setState() within initState(). This is when you have a callback function within initState() that may be triggered after initState() has already completed execution. Say you are fetching a firebase document within initState() and as soon as you get the document, you want to set a variable. However, the document fetching may take time, and by then, the first build may have already happened. In such a scenario, calling setState() within initState() makes sense. The example below illustrates this point better:

  void initState() {
    initCount = 1; //This doesn't require setState()
    .then((DocumentSnapshot documentSnapshot) {
            userName = documentSnapshot.userName; //setState() Required here

That’s it. I hope this article makes it clear when to use setState() within initState().


If you liked this article, then checkout other articles on

Leave a comment

Your email address will not be published.