Sub topic 1
How a Flutter app is a tree of widgets
Prerequisites
This chapter assumes you know basic Dart syntax, including classes, constructors, and named parameters. You should understand StatelessWidget and its build method, and you should have a Flutter SDK that can run an app.
How a Flutter app is a tree of widgets
Flutter builds every screen from widgets. A widget is an immutable class that describes one part of the interface. Widgets nest inside other widgets, so the whole interface forms a tree. The root sits at the top, and each child sits inside its parent. When Flutter draws the screen, it walks this tree from the top down.
MaterialApp: the root of a Material app
MaterialApp is the root widget for apps that follow Material Design. It sets the app title, the theme, the home screen, and any named routes. You pass it to runApp once. Every other widget in the app sits below it in the tree.
Setting the theme
The theme parameter takes a ThemeData. Its ColorScheme.fromSeed constructor builds a full set of colors from one seed color. Setting useMaterial3: true opts into the current Material 3 styles.
Scaffold: the structure of a screen
Scaffold gives a screen its standard layout slots: appBar, body, floatingActionButton, and drawer. You fill only the slots you need. The Scaffold places each one in the correct position.
AppBar: the top bar of a screen
AppBar fills the appBar slot. Its title parameter sets the heading text. Its actions parameter takes a list of buttons shown at the right side of the bar.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
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: Text('Hello, Flutter')),
);
}
}Exercise
Exercise
In the example, what widget would you place in the Scaffold's body slot to show a different message, and why does the AppBar stay at the top when the body changes?
Show answer
Replace the Center widget with another widget, such as a Text or a ListView. The AppBar stays at the top because the Scaffold places the appBar slot in a fixed position and the body slot fills only the space below it.