ข้ามไปยังเนื้อหา

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.statefields บน class State<T>
setState(newVal)setState(() { field = newVal; })
Component function / render()State.build(BuildContext)
useEffect(fn, []) — mountinitState()
useEffect(fn, [dep]) — prop changedidUpdateWidget(oldWidget)
useEffect(() => cleanup, []) — unmountdispose()
useContext / React ContextInheritedWidget / BuildContext
React key propFlutter Key บน widget
  1. State & Lifecycle overview ← คุณอยู่ที่นี่
  2. setState vs useState — mutable state API
  3. build() vs render() — pure rebuild model ของ Flutter
  4. Lifecycle เชิงลึกinitState, didChangeDependencies, didUpdateWidget, dispose
  5. Rebuilds & Keysconst widgets, identity, และ reconciliation
ทำไม Flutter ต้องแยก StatefulWidget ออกจาก State class?
React hook ใดที่ใกล้เคียงกับ initState() ของ Flutter มากที่สุด?
Flutter method ใดที่เทียบเท่ากับ cleanup function ของ useEffect?