CodeBlanks Logo Icon CodeBlanks

Widget tree

Learn how the widget tree forms and updates.

Widget tree

The widget_tree is the abstract tree formed by nested widgets in Flutter. Every widget is immutable, meaning it cannot be modified; when state changes, a new widget object is created and the tree is rebuild.

MaterialApp(
  home: Scaffold(
    body: Center(
      child: Text('Hello'),
    ),
  ),
)

Rebuild process

rebuild is the re-invocation of the build method. When state changes, the related widget and its descendants are recreated via build. Each rebuild produces new widget objects, but the old Element tree is kept so updates are efficient.

Practice Build a widget tree

In main, create a MaterialApp widget: home is a Scaffold, body is Center, child is Text('Merhaba'). Print the widget's runtimeType.

Starter code

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

void main() {
  // MaterialApp, Scaffold, Center ve Merhaba metnini iç içe oluştur
  // runtimeType yazdır
}

Sample solution

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

void main() {
  final widget = MaterialApp(
    home: Scaffold(
      body: Center(
        child: const Text('Merhaba'),
      ),
    ),
  );
  print(widget.runtimeType);
}

Expected output

MaterialApp

Questions and answers

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

1 What happens when a widget's state changes?

  • The app crashes
  • Nothing happens
  • A new widget object is created and the tree is rebuilt Correct answer
  • The widget object is modified

Explanation: Since widgets are immutable, when state changes the widget object cannot be updated; a new one is created and the build method is invoked again.

2 Add Center to the widget tree

Question
MaterialApp(
  home: Scaffold(
    body: ____(child: Text('Merhaba')),
  ),
)
Answer
MaterialApp(
  home: Scaffold(
    body: Center(child: Text('Merhaba')),
  ),
)

Explanation: Center centers its child; in the widget tree it is used as the child of the Scaffold body.

3 Widget tree matches

Term Meaning
widget_tree Nested widget arrangement
immutable Cannot be modified
rebuild Re-invokes build
build Returns a widget

All lessons in Expert