Flutter - Stateless Widgets

Flutter 的 Stateless widget 指的是無狀態的 widget。


使用時會建立一個繼承自 StatelessWidget 的子類別,然後複寫處理 build 方法,在該方法描述要怎樣建立該 widget。

1
2
3
4
5
6
7
8
9
...
class MyWidget extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
...
}
}
...


像是下面這邊筆者就試著建立了一個簡單的 widget,用 Container widget 與 Icon widget 搭配,簡單的做了類似於 Button 的效果,並允許由 widget 外部注入去決定要呈現的 icon。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import 'package:flutter/material.dart';

void main() {
runApp(
new MaterialApp(
home: new Center
(
child: new MyWidget(icon: Icons.add)
)
)
);
}

class MyWidget extends StatelessWidget {
MyWidget({this.icon});
final IconData icon;
@override
Widget build(BuildContext context) {
return new Container(
width: 200.0,
height: 100.0,
color: Colors.green,
child: new Icon
(
icon,
color: Colors.white
));
}
}