大多數的頁面到需要 State,如經典的 Counter,可簡單地使用 StatefulWidght
實現。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
StatefulWidget
實現 counter
StatefulWidget
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
class _Home extends State<Home> {
var _count = 0;
Widget build(BuildContext context) {
var appBar = AppBar(title: const Text('Counter'));
var floatingActionButton = FloatingActionButton(
onPressed: () {
setState(() => _count++);
},
child: const Icon(Icons.add));
var body = Center(child: Text('$_count'));
return Scaffold(
appBar: appBar,
floatingActionButton: floatingActionButton,
body: body,
);
}
}
- Stateful 頁面需由兩個 class 構成
StatefulWidget
:啟動 StateState
:實質控制 state 與顯示 UI
Line 3
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
- 定義
Home
page,繼承自StatefulWidget
class - 在
createState()
會回傳_Home
state
Line 12
class _Home extends State<Home> {
}
- 定義
_Home
state class
Home_
寫在後面
會違反 Dart 命名規則
Line 13
var _count = 0;
- 定義
_count
state
Private field 與 private method 在 Dart 的 naming convention 會加上
_
Line 27
return Scaffold(
appBar: appBar,
floatingActionButton: floatingActionButton,
body: body,
);
- 建立
Counter
的 UI
Line 17
var appBar = AppBar(
title: const Text('Material StatelessWidget'),
);
- 建立
MaterialApp
的appBar
Line 19
var floatingActionButton = FloatingActionButton(
onPressed: () {
setState(() => _count++);
},
child: const Icon(Icons.add));
onPressed()
:處理FloatingActionButton
的onPressed
eventsetState()
:寫入 state
Line 25
var body = Center(child: Text('$_count'));
- 建立
MaterialApp
的body
Conclusion
- 實務上大多會使用
StatefulWidget
建立頁面,有些 Widget 還會指定搭配StatefulWidget
,如NavigationBar