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

第 3 課:小部件樹和基本小部件

Widget 樹、Element 樹、RenderObject 樹。 StatelessWidget 與 StatefulWidget。文字、圖像、圖示、按鈕小工具。 MaterialApp、支架、AppBar。熱重載/重啟。

💻 程式設計 — 第 3 課 第 3 課:小部件樹和基本小部件

Flutter 和 Dart:從基礎到高級

第 1 部分:Dart 和 Flutter 基礎知識

亞洲開發網

1. 部件樹

Flutter 有 3 棵樹: 小部件樹 (使用者介面描述), 元素樹 (生命週期管理), 渲染物件樹 (佈局和油漆)。每次 setState() 時,Flutter 都會重建 widget 樹,但在可能的情況下重複使用元素。

2.StatelessWidget 與 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. 基本小工具

// 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: 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),
  ),
);

下一篇: 佈局和響應式設計。