Widget Tree and Element Tree
Now, as the user interface contains several widgets, those several widgets are combined to form a widget tree.
Now, to each widget that the user creates, an element is created simultaneously by the flutter framework, so now
these elements when combined will be called an element tree.
So that means that the widget tree has all the widget configuration and the element tree has all rendered
widgets on the screen. There is one more tree named render tree, but the user doesn’t have to interact with it.
Render tree is basically a low-level layout, painting system that inherits from the render objects. You won’t
need to inherit directly to the render tree, and you will be interacting with the widgets.
- STATELESS WIDGET AND ELEMENT TREE:
- STATEFUL WIDGET AND ELEMENT TREE:
Stateless widget is the widget that is used by the user to create a non-dynamic application. A stateless widget is formed by a combination of several small widgets. Each widget that is created here will have a corresponding stateless element. So several widgets combined under stateless widgets will be called stateless widget trees and the corresponding elements will make an element tree. Flutter uses the createElement method to create the elements. Each element created will have a unique id assigned by the flutter back-end.
Example :
class TextList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Icon(...),
Text(...),
],
);
}
}
Here in this code, we have created a simple class called TextList which extends the stateless widget, which contains several other widgets like row, icon, and text. For each widget in this widget tree, a stateless element is created and the combination of these elements makes it an element tree.
A stateful widget is a widget that is used by the user to create a dynamic application. The stateful widget
also works similar to the stateless widget, but here when the framework calls the createElement method, a
state object is created. The reason behind creating the state object is that as this has to be a dynamic
application the states would change while keeping the previous state unharmed and enhancing the performance.
We make use of the setState method to set the new data values or to update the state objects.
Example :
class _TextListState extend State<TextList> {
String note = 'Trip A';
void _onPressed() {
setState( () {
note = 'Trip B';
});
}
@override
Widget build (BuildContext xontext){
return Column(
children : <Widget> [
Icon(....);
Text('$note'),
FlatButton(
onPressed : _onPressed,
),
],
);
}
Here in this code, we have created _TextListState class that extends the state TextList. We have used the setState method because we have to keep the initial state in the element tree even after changing the state.
source : geeksforgeeks