Widgets & Widget Tree
In Flutter, everything is a widget. Widgets are the building blocks of your app's UI. They can be combined to create complex interfaces from simple, reusable pieces.
The Widget Tree
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Widget Tree โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ MaterialApp โ
โ โ โ
โ Scaffold โ
โ / \ โ
โ AppBar Body โ
โ โ โ
โ Column โ
โ / \ โ
โ Text Row โ
โ / \ โ
โ Icon Text โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
StatelessWidget vs StatefulWidget
Flutter has two types of widgets:
- StatelessWidget: Immutable, doesn't change over time (labels, icons, static content)
- StatefulWidget: Mutable, can change its state (forms, counters, any interactive element)
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('My App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.star, size: 100, color: Colors.amber),
SizedBox(height: 20),
Text(
'Welcome to Flutter!',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
],
),
),
),
);
}
}
StatefulWidget Example
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: $_count', style: TextStyle(fontSize: 32)),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => setState(() => _count++),
child: Icon(Icons.add),
),
SizedBox(width: 20),
ElevatedButton(
onPressed: () => setState(() => _count--),
child: Icon(Icons.remove),
),
],
),
],
);
}
}