State & Lifecycle
ใน React นั้น state อยู่ ภายใน component เอง — ไม่ว่าจะเป็น hook variable จาก useState หรือ this.state ใน class component เมื่อ state เปลี่ยน React จะ re-render component function (หรือเรียก render())
Flutter แยกความรับผิดชอบออกจากกันต่างออกไป StatefulWidget คือ object การกำหนดค่าที่ไม่เปลี่ยนแปลง (เหมือน props/JSX tag) และ class State<T> ที่เป็นคู่กันจะเก็บ state ที่เปลี่ยนแปลงได้และเป็นเจ้าของ method build() ทั้งสองทำงานร่วมกัน: widget ให้ identity และ configuration; state ให้ความจำและ lifecycle
ทำไมต้องแยก?
หัวข้อที่มีชื่อว่า “ทำไมต้องแยก?”Widget tree ของ Flutter ถูก rebuild บ่อยมาก — การ rebuild ของ ancestor ใดก็ตามสามารถสร้าง widget objects ใหม่ได้ ถ้า state อยู่บน widget เอง state จะถูกทำลายทุกครั้งที่ rebuild ด้วยการเก็บ state ไว้ใน object State แยกต่างหากที่มีอายุยาวกว่าซึ่ง Flutter จัดการ การสร้าง widget description ใหม่จึงราคาถูก ส่วน state ยังคงอยู่ข้ามการ rebuild
| แนวคิดจาก React | เทียบเท่าใน Flutter |
|---|---|
useState / this.state | fields บน class State<T> |
setState(newVal) | setState(() { field = newVal; }) |
Component function / render() | State.build(BuildContext) |
useEffect(fn, []) — mount | initState() |
useEffect(fn, [dep]) — prop change | didUpdateWidget(oldWidget) |
useEffect(() => cleanup, []) — unmount | dispose() |
useContext / React Context | InheritedWidget / BuildContext |
React key prop | Flutter Key บน widget |
บทเรียนในโมดูลนี้
หัวข้อที่มีชื่อว่า “บทเรียนในโมดูลนี้”- State & Lifecycle overview ← คุณอยู่ที่นี่
- setState vs useState — mutable state API
- build() vs render() — pure rebuild model ของ Flutter
- Lifecycle เชิงลึก —
initState,didChangeDependencies,didUpdateWidget,dispose - Rebuilds & Keys —
constwidgets, identity, และ reconciliation