skip to Main Content

When setState is called in a widget’s state, the corresponding element in the element tree gets marked as dirty, and the widget gets rebuilt. However, how does it handle descendents? For example, the Text widget below gets rebuilt when its ancestor SampleWidgetState gets rebuilt.

Why?

class SampleWidget extends StatefulWidget {
  @override
  SampleWidgetState createState() => SampleWidgetState();
}

class SampleWidgetState extends State<SampleWidget> {
  String text = "text1";

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(text),
        ElevatedButton(
          child: Text('call SetState'),
          onPressed: () {
            setState(() {
              text = "text2";
            });
          },
        ),
      ],
    );
  }
}

2

Answers


  1. from Flutter’s official documentation, inside Flutter:

    In response to user input (or other stimuli), an element can become dirty, for example if the developer calls setState() on the associated state object. The framework keeps a list of dirty elements and jumps directly to them during the build phase, skipping over clean elements. During the build phase, information flows unidirectionally down the element tree, which means each element is visited at most once during the build phase. Once cleaned, an element cannot become dirty again because, by induction, all its ancestor elements are also clean.

    I guess this answer what Flutter does under the hood in the updating process of the widget’s descendents.

    Login or Signup to reply.
  2. SampleWidgetState is a state class, when you calling the setState() its mean build() method will reinvoke, everything inside will rebuild. thats how its works.

    if you want to prevent the descendents to not rebuild, there is several ways,

    1. use const keyword.
    2. warp the widget you want to change its own state, example use StatefullBuilder
    3. refactor widget to statefulwidget so its have its own state

    in your case, Text widget consume SampleWidgetState : String text = "text1";, its mean Text widget is not independent, its dependent on that state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search