Managing states within a widget with setState
This is the simplest approach you can use to change states inside your Flutter application whenever a user interacts with it. This uses a simple function call (known as setState
) which, whenever called, rebuilds the widget (that is, runs the build method again) that you called the function in. This also rebuilds every other widget that is under that specific widget tree. A widget tree is something that contains widgets being built inside widgets. So, in the case where a widget rebuilds due to a user interaction, all the widgets inside it are also going to rebuild themselves. This section will also include an optional challenge where you will learn how to perform the optimized rebuilding of widgets.
The counter application example
Let's jump to the most basic example which uses setState
to change states. This example can also be seen in the sample Flutter application which is created through the flutter doctor
command.
If...