DEV Community

Gilbish
Gilbish

Posted on

Will the whole MainWidget re-render or just the Wrapping widget which is using the state in flutter whenever setState is called?

I am new to Flutter , i was going through flutter doc and a doubt came to me, how the re-render or re building of UI works in flutter?

If i have two widgets under my Main Widget and i am using a state in the 2nd widget, will the first widget also get re-rendered? 🧐

class MainWidget extends StatefulWidget {
  @override
  _MainWidgetState createState() => _MainWidgetState();
}

class _MainWidgetState extends State<MainWidget> {
  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('This is the second widget'),
        Text('Counter: $counter'),
        ElevatedButton(
          onPressed: () {
            incrementCounter();
          },
          child: Text('Increment Counter'),
        ),
      ],
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Whenever the user Clicks the Increment Counter Button, the state will get updated, in response the UI should get re rendered.

But the question is will the **whole MainWidget** is **re-rendered** or just the **Text Widget** which is using the counter state?

Answer:

When you call setState, it schedules a rebuild of the widget, and the build method is called again. However, this does not necessarily mean that the entire MainWidget and its subtree will be rebuilt from scratch every time setState is called.

Flutter is designed to be efficient, and it employs a process called "reconciliation" to update the widget tree efficiently.

  1. When setState is called, Flutter marks the widget as dirty and schedules it for rebuilding.

  2. The next time the Flutter framework performs a frame update (typically 60 times per second), it checks which widgets are marked as dirty and calls their build methods.

  3. During the build process, Flutter compares the new widget tree with the previous one (the one from the previous frame) and identifies the differences (what needs to be added, updated, or removed).

  4. Flutter updates only the parts of the widget tree that have changed. This means that only the widgets and elements affected by the state change get rebuilt, while unchanged parts of the widget tree are reused.

So after the setState only the Widget which is using the counter state in it will be rebuilt.

 @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('This is the second widget'), // re-render ❌
        Text('Counter: $counter'), //  re-render βœ…
        ElevatedButton(
          onPressed: () {
            incrementCounter();
          },
          child: Text('Increment Counter'), //re-render ❌
        ),
      ],
    );
  }
Enter fullscreen mode Exit fullscreen mode

Thanks for the reading. πŸ˜‡

Top comments (0)