CodeBlanks Logo Icon CodeBlanks

Element tree

Learn that the element tree bridges widget and render trees.

Element tree

The Element tree is the bridge between the widget tree and the render tree. For each widget an Element is created; the element mounts the widget, and holds state and context. Even though widgets are recreated on every rebuild, elements are kept and only updated.

// For each StatelessWidget an Element is created
element.update(newWidget);

mount and update

mount is the first insertion of the element into the tree; update is the refresh of an existing element with a new widget. Because elements are kept, rebuild is cheap: only update is called.

Practice Define a StatelessWidget

Define MyWidget as a StatelessWidget. Its build method returns Container(child: Text('Selam')). In main, take a const MyWidget() instance and print its runtimeType.

Starter code

main.dart
import 'package:flutter/material.dart';

// MyWidget StatelessWidget olsun
// build metodu Selam metnini içeren bir Container döndürsün

void main() {
  // MyWidget örneği al ve runtimeType yazdır
}

Sample solution

main.dart
import 'package:flutter/material.dart';

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(child: const Text('Selam'));
  }
}

void main() {
  final widget = const MyWidget();
  print(widget.runtimeType);
}

Expected output

MyWidget

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the Element tree bridge?

  • Memory and disk
  • State and BuildContext
  • Two widgets
  • Widget tree and render tree Correct answer

Explanation: The Element tree is the intermediate layer that connects the widget tree (abstract definition) to the render tree (drawing); one element is created per widget.

2 Update the element

Question
element.____(newWidget);
Answer
element.update(newWidget);

Explanation: When an existing element is refreshed with a new widget, update is called; mount is only for first insertion, dispose for removal from the tree.

3 Element tree matches

Term Meaning
Element Widget-render binder
mount First insertion to tree
update Update when widget changes
BuildContext The element itself

All lessons in Expert