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'),
),
],
);
}
}
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.
When setState is called, Flutter marks the widget as dirty and schedules it for rebuilding.
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.
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).
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 β
),
],
);
}
Thanks for the reading. π
Top comments (0)