Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 73 ยท Widgets and the widget tree

Everything Is a Widget

Understand Flutter's core idea: everything is a widget. Learn StatelessWidget, the build method, the widget tree, Text, Container, Center, MaterialApp and Scaffold.

In Flutter, the screen is described by widgets. A button is a widget. The text on it is a widget. The padding around the text is a widget. The invisible thing that centers it is a widget. Even your whole app is a widget. You build an interface by nesting small widgets inside bigger ones until they form a widget tree.

This idea is simple but it changes how you think. You do not create a button object and then mutate it ("set the color, set the label"). You write a function that describes what the screen should look like right now, and Flutter makes the screen match. This lesson shows how to write that description with StatelessWidget, how the common building blocks fit together, and how a minimal widget tree works inside. Before this, you should know Dart classes and have run an app as in Setting up and running your first app.

Real vs stand-in. The Dart code below is real Flutter code, shown read-only because the site has no Dart runtime. The live examples are JavaScript stand-ins: a tiny widget tree whose build methods return descriptions, which is exactly how the real framework is organized, minus rendering pixels.

A screen is a tree

Small widgets Each does one job.
Nesting Widgets contain other widgets.
One tree Together they form the widget tree.
1 / 2

Your first widget

A widget that never changes by itself extends StatelessWidget. Its only real job is the build method, which returns another widget.

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

class Greeting extends StatelessWidget {
  const Greeting({super.key, required this.name});

  final String name;

  @override
  Widget build(BuildContext context) {
    return Text('Hello, $name!');
  }
}

Four details matter here:

  • Fields are final. A widget is an immutable description. To show something different you create a new widget with new values, you do not edit the old one.
  • const constructor. When all inputs are compile-time constants, Flutter can reuse one object and skip work. Mark constructors const whenever possible.
  • super.key. Every widget accepts an optional Key, used for identity (Keys and widget identity).
  • BuildContext context. It tells the widget where it sits in the tree (BuildContext and InheritedWidget).

You use it like any other widget: Greeting(name: 'Mina'). Notice there is no new; Dart does not need it.

Composing with common widgets

Flutter's library is a big collection of small, single-purpose widgets that you combine.

  • Text('hi') draws a string, and style: customizes it with TextStyle.
  • Center(child: ...) centers its child inside the space available.
  • Container(...) is a convenience widget: it can add color, padding, margin, a border, a size and more around one child.
  • Padding, SizedBox, Row, Column, Stack and many others handle spacing and arrangement. You will study them in the layout chapter, starting with Constraints go down, sizes go up.
DART
class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.indigo.shade50,
          borderRadius: BorderRadius.circular(12),
        ),
        child: const Text(
          'Mina Park',
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

Read it from the outside in: a Center holds a Container, which has padding and a rounded colored background, and holds a Text. The tree is Center โ†’ Container โ†’ Text. Single-child widgets use child:; widgets with several children use children: [...].

The app shell: MaterialApp and Scaffold

Every Flutter app starts with runApp, which takes the root widget and attaches it to the screen.

DART
void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter',
      theme: ThemeData(colorSchemeSeed: Colors.indigo),
      home: const HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: const Center(child: Greeting(name: 'Mina')),
    );
  }
}

MaterialApp provides the things almost every app needs: a theme, a navigator for screens (Navigator and routes), text direction, localization and the home page. Scaffold is the skeleton of one Material screen: it has slots for an appBar, a body, a floatingActionButton, a drawer and a bottomNavigationBar. Later chapters explore them in Material 3 widgets tour and Themes, colors and dark mode.

The full tree here is MyApp โ†’ MaterialApp โ†’ HomePage โ†’ Scaffold โ†’ (AppBar โ†’ Text) + (Center โ†’ Greeting โ†’ Text). Some of those widgets are yours, some come from Flutter, and the framework treats them all the same way.

What build really means

The build method has two rules.

  1. Return a description quickly. Flutter may call build many times, for example on every frame of an animation. Do not fetch data, open files or do heavy work in it.
  2. Be a pure function of its inputs. The same fields and context should produce the same widgets. Avoid side effects such as printing, timers, or changing variables.

Because widgets are small immutable objects, creating hundreds of them per frame is cheap. Why that is fast is the topic of the next lesson, Widget, Element and RenderObject trees.

A widget tree stand-in

To see the mechanism clearly, here is a tiny version in JavaScript. A "widget" is a function that returns either a primitive description (like text) or another widget; build is called recursively until only primitives remain.

JS Mini widget tree: build until primitives

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is the whole tree, from your custom MyApp down to the primitive Text. In real Flutter, the primitives are RenderObjectWidgets that create objects which lay out and paint. The composite widgets (StatelessWidget) just delegate to what they return from build.

Rebuilding is just calling build again

A StatelessWidget does not change on its own, but its parent can give it new values. The parent builds again, creates a new Greeting('Noor'), and the framework updates the screen to match. The next TryIt simulates a parent producing different descriptions and shows that old and new descriptions are different objects, as in Flutter.

JS Descriptions are cheap, immutable values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(In the real framework the freeze is enforced by final fields: you cannot assign to them, because the code would not compile.)

Common mistakes

  • Putting state in a StatelessWidget. A non-final field you mutate will not trigger a rebuild. Use StatefulWidget and setState.
  • Giant build methods. If a method grows past a screenful, extract a new widget class. Prefer new classes over helper methods that return widgets, so const and rebuild optimizations still work.
  • Missing const. The analyzer will suggest it; accept the suggestion.
  • Expecting a widget to "be" the on-screen object. A widget is a blueprint. The framework owns the real objects behind it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main job of a StatelessWidget's build method?

    build returns another widget that describes part of the UI. It should be quick and free of side effects.
  2. 2. Why are the fields of a widget usually final?

    A widget is an immutable blueprint. To show different data, a parent builds a new widget instance.
  3. 3. Which widget is the skeleton of a Material screen, with slots such as appBar and body?

    Scaffold provides the standard screen layout slots. MaterialApp sits above it and supplies theme and navigation.
  4. 4. Where is the best place to put heavy work such as parsing a large file?

    build can run many times, even every frame, so it must stay cheap.

Summary

  • A Flutter UI is a tree of widgets; every part of the screen, even layout and the app itself, is a widget.
  • A StatelessWidget has final fields and a build method that returns a description of its UI.
  • Text, Center, Container and friends are small building blocks you nest with child and children.
  • MaterialApp provides theme and navigation; Scaffold provides the screen skeleton.
  • Keep build fast and pure, use const constructors, and extract widget classes instead of giant methods.

Next: Widget, Element and RenderObject Trees