點燈坊

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

建立 Stateless 頁面

Sam Xiao's Avatar 2024-08-26

當整個頁面到不需要 State 時,可簡單地使用 StatelessWidght 即可。

Version

Flutter 3.24
Dart 3.5

Flutter

stateless01

  • Android 與 iOS 都成功使用 StatelessWidget 顯示 Hello World

Main

main.dart

import 'package:flutter/material.dart';

import 'HelloWorld.dart';

void main() {
  runApp(const HelloWorld());
}
  • Import 自己建立的 hello_world.dart
  • 建立 HelloWorld widget 並傳入 runApp() 顯示在 view

StatelessWidget

HelloWorld.dart

import 'package:flutter/material.dart';

class HelloWorld extends StatelessWidget {
  const HelloWorld({super.key});

  
  Widget build(BuildContext context) {
    return const Center(
      child: Text(
        'Hello World',
        textDirection: TextDirection.ltr,
      ),
    );
  }
}
  • 使用 StatelessWidget 建立頁面

Line 3

class HelloWorld extends StatelessWidget {
}
  • 自己的頁面要繼承自 StatelessWidget class

Line 4

const HelloWorld({super.key});
  • Class 的 constructor

Line 6


Widget build(BuildContext context) {
  return const Center(
    child: Text(
      'Hello World',
      textDirection: TextDirection.ltr,
    ),
  );
}
  • Override build() 建立自己的畫面

Conclusion

  • 雖然 HelloWorld 可不用 StatelessWidget 亦可建立,但實務上會使用 StatelessWidget