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

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

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:

  @override
  void initState() {
    initCount = 1; //This doesn't require setState()
    FirebaseFirestore.instance
    .collection('users')
    .doc(userId)
    .get()
    .then((DocumentSnapshot documentSnapshot) {
        setState((){
            userName = documentSnapshot.userName; //setState() Required here
        });
    });
    super.initState();
  }

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

Reference: https://stackoverflow.com/a/53373017


If you liked this article, then checkout other articles on https://iotespresso.com.

Leave a comment

Your email address will not be published.