當整個頁面到不需要 State 時,可簡單地使用 StatelessWidght
即可。
Version
Flutter 3.24
Dart 3.5
Flutter
- 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
build(BuildContext context) {
return const Center(
child: Text(
'Hello World',
textDirection: TextDirection.ltr,
),
);
}
Widget
- Override
build()
建立自己的畫面
Conclusion
- 雖然 HelloWorld 可不用
StatelessWidget
亦可建立,但實務上會使用StatelessWidget