1. ウィジェットツリー
Flutter には 3 つのツリーがあります。 ウィジェットツリー (UIの説明)、 要素ツリー (ライフサイクル管理)、 レンダーオブジェクトツリー (レイアウトとペイント)。 setState() を実行するたびに、Flutter はウィジェット ツリーを再構築しますが、可能な場合は要素を再利用します。
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),
),
);
次の記事: レイアウトとレスポンシブデザイン。