Understand Flutter's big idea, the widget tree, through three basic building blocks: Text, Container, and Icon.
Open this lesson in KodokonIn Flutter, everything is a widget. A widget is an interface building block: the description of a piece of what appears on screen. A text is a widget, an icon is a widget, a spacing is a widget... and the whole screen too! To build an interface, you nest widgets inside one another, like Russian dolls. Together they form the widget tree: each widget has a parent (the one containing it) and sometimes children (the ones it contains). Let's revisit our minimal program and look at its tree.
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(
theme: ThemeData(useMaterial3: true),
home: const Scaffold(
body: Center(
child: Text(
"Everything is a widget!",
style: TextStyle(fontSize: 24),
),
),
),
);
}
}From top to bottom: MaterialApp configures the whole app (theme, navigation) following Material 3, Google's visual language. Scaffold (literally "scaffolding") provides the structure of a screen: background, an optional title bar... Center centers its child, and Text displays text. The style parameter of Text receives a TextStyle that sets the size (fontSize), the color, or the weight of the characters. Now let's discover Container, the do-it-all box: a rectangle whose size, color, and contents you control.
import 'package:flutter/material.dart';
Widget buildYellowBox() {
return Container(
width: 200,
height: 100,
color: Colors.amber,
child: const Center(
child: Text("I'm inside a box"),
),
);
}The buildYellowBox function returns a widget: splitting your interface this way into small named pieces is a very common practice. This Container is 200 pixels wide, 100 tall, paints itself amber yellow thanks to the Colors color catalog, and holds a centered text. Third basic building block: Icon, which displays a pictogram. Flutter ships hundreds of ready-to-use icons in the Icons catalog: a star, a heart, a house...
import 'package:flutter/material.dart';
Widget buildStar() {
return const Icon(
Icons.star,
size: 48,
color: Colors.orange,
);
}Remember the logic of the tree: when a widget accepts a single child, the parameter is called child (that's the case with Center and Container). In our first example, Scaffold is the parent of Center, which is the parent of Text. Flutter draws the screen by walking this tree from top to bottom. If you can tell who the parent of whom is, you can read any Flutter interface.
Center(child: Text("Hi")), which widget is the parent?