點燈坊

失くすものさえない今が強くなるチャンスよ

StatefulWidget 建立 Stateful 頁面

Sam Xiao's Avatar 2024-10-19

大多數的頁面到需要 State,如經典的 Counter,可簡單地使用 StatefulWidght 實現。

Version

Flutter 3.24

Flutter

stateful01

  • 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:啟動 State
    • State:實質控制 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'),
);
  • 建立 MaterialAppappBar

Line 19

var floatingActionButton = FloatingActionButton(
  onPressed: () {
    setState(() => _count++);
  },
  child: const Icon(Icons.add));
  • onPressed() :處理 FloatingActionButtononPressed event
  • setState():寫入 state

Line 25

var body = Center(child: Text('$_count'));
  • 建立 MaterialAppbody

Conclusion

  • 實務上大多會使用 StatefulWidget 建立頁面,有些 Widget 還會指定搭配 StatefulWidget,如 NavigationBar