Chip’s Tips: The Do’s and Don’ts Of Flutter

Week 1: When and Where to Call setState()

GroovinChip
1 min readMay 15, 2021

Please note: This article assumes the reader has a basic working knowledge of Flutter

Welcome to Chip’s Tips, a new series of weekly articles where I’ll be sharing tips and tricks to improve your skills as a Flutter developer!

This week we’ll be discussing our good old friend setState(). We all know what setState() does — it lets us tell Flutter that something has changed in the State of our widget and we’d like the widget to be rebuilt so that we can see the change. Unfortunately, there is often some confusion about when and where to call setState(), so let’s clear that up and then we’ll take a look at some code.

Let’s take a look setState()’s documentation:

After reading this, we can determine the following rules:

Do no call setState():

  1. Directly inside initState(), where state is already being initialized
  2. Directly inside of a Widget build method, where the widget is being built
  3. Directly inside of a Widget’s builder callback where the widget is being built
  4. After a widget’s dispose method is called

Where it is appropriate to call setState():

  1. Within a widget’s VoidCallback function, like onPressed, onTap, or onLongPress
  2. Within a function that is called by a widget’s VoidCallback.
  3. Within a function that is called by initState()

And there we have it! The do’s and don’ts of setState(). I hope you’ve found this helpful. Stay tuned for next week’s article!

--

--