Flutter Widget Tree vs. Element Tree vs. Render Tree: Understanding Their Role & Relationship
Imagine You’re Building a House 🏠
- Widget Tree → The blueprint or plan of the house.
- Element Tree → The workers and engineers who follow the plan and manage the construction.
- Render Tree → The actual house that gets built and becomes visible.
Real Flutter Example: Button UI Update
Imagine you have a simple Flutter app with a button that changes the text when pressed.
Code Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String buttonText = "Click Me!";
void updateText() {
setState(() {
buttonText = "Clicked!";
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Flutter Trees Example")),
body: Center(
child: ElevatedButton(
onPressed: updateText,
child: Text(buttonText),
),
),
);
}
}
How Flutter Uses the Three Trees
Step 1: Widget Tree (Blueprint 📜)
- Initially, Flutter creates a widget tree based on your code.
- This tree consists of:
Scaffold
AppBar
Center
ElevatedButton
Text(buttonText)
💡 Remember: Widgets are immutable (cannot change). If something changes, a new widget is created.
Step 2: Element Tree (Workers 👷♂️)
- Flutter creates an Element Tree to keep track of each widget’s position, lifecycle, and updates.
- Each widget is mapped to an Element (which is mutable).
- When you call
setState()
, Flutter doesn’t rebuild the whole UI—only the parts that need updates.
🔹 Example:
- The
Text(buttonText)
element is updated with"Clicked!"
instead of recreating the whole UI.
Step 3: Render Tree (Actual House 🏡)
- The Render Tree handles the actual drawing on the screen.
- It converts elements into pixel information and decides what needs to be repainted.
- Instead of repainting everything, it only updates the changed part (
Text
inside the button).
🔹 Example:
- Only the text inside the button (
Click Me!
→Clicked!
) is repainted. - The
Scaffold
,AppBar
, andElevatedButton
remain unchanged.
What Happens When You Press the Button?
setState()
is called → Flutter marks theText(buttonText)
widget as dirty.- The Widget Tree creates a new
Text
widget (Clicked!
). - The Element Tree compares the old and new widgets and updates the existing
Element
. - The Render Tree only repaints the changed
Text
inside the button, keeping everything else the same.