Chuyển đến nội dung chính

Lesson 3: Widget Tree & Basic Widgets

Widget tree, Element tree, RenderObject tree. StatelessWidget vs StatefulWidget. Text, Image, Icon, Button widgets. MaterialApp, Scaffold, AppBar. Hot reload/restart.

💻 Programming — Lesson 3 Lesson 3: Widget Tree & Basic Widgets

Flutter & Dart: From Basics to Advanced

Part 1: Dart & Flutter Fundamentals

xdev.asia

1. Widget Tree

Flutter has 3 trees: Widget Tree (UI description), Element Tree (lifecycle management), RenderObject Tree (layout & paint). Every time setState(), Flutter rebuilds the widget tree but reuses elements when possible.

2. StatelessWidget vs StatefulWidget

// StatelessWidget — không có state nội tại
class Greeting extends StatelessWidget {
  final String name;
  const Greeting({super.key, required this.name});

  @override
  Widget build(BuildContext context) {
    return Text('Xin chào, $name!');
  }
}

// StatefulWidget — có state thay đổi
class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> 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: Theme.of(context).textTheme.headlineMedium),
        const SizedBox(height: 16),
        ElevatedButton(
          onPressed: () => setState(() => _count++),
          child: const Text('Tăng'),
        ),
      ],
    );
  }
}

3. Basic Widgets

// Text
Text('Hello', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold));

// Image
Image.network('https://example.com/image.jpg', fit: BoxFit.cover);
Image.asset('assets/images/logo.png');

// Buttons
ElevatedButton(onPressed: () {}, child: Text('Elevated'));
TextButton(onPressed: () {}, child: Text('Text'));
OutlinedButton(onPressed: () {}, child: Text('Outlined'));
IconButton(onPressed: () {}, icon: Icon(Icons.favorite));

// Card
Card(
  elevation: 4,
  child: ListTile(
    leading: Icon(Icons.star),
    title: Text('Title'),
    subtitle: Text('Subtitle'),
    trailing: Icon(Icons.arrow_forward_ios),
  ),
);

4. Scaffold & AppBar

Scaffold(
  appBar: AppBar(
    title: const Text('My App'),
    actions: [
      IconButton(onPressed: () {}, icon: const Icon(Icons.search)),
    ],
  ),
  body: const Center(child: Text('Content')),
  bottomNavigationBar: NavigationBar(
    destinations: const [
      NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
      NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
    ],
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: () {},
    child: const Icon(Icons.add),
  ),
);

Next article: Layouts & Responsive Design.