runApp()
runApp(widget)
啟動App的入口runApp()。
1
2
3
void main() {
runApp(const MyApp());
}
語法:
runApp(Widget)
runApp()參數為Widget,flutter中,所有東西都是Widget所組成。
Widget 中文是佈局元件。
MaterialApp()
MaterialApp()是Google的視覺化主題佈局元件。
參數有 title(標題)、theme(主題)、home 為App的Body。
MaterialApp(
title: '標題名稱',
theme: 視覺化主題,
home: Scaffold()
)
1
2
3
4
5
6
7
8
9
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Flutter Base',
theme: ThemeData(scaffoldBackgroundColor: Colors.blue),
home: Scaffold()
));
}
Scaffold() 骨架
| 屬性 | 說明 |
|---|---|
| appBar | app標題 |
| body | 主要內容 |
| bottomNavigationBar | 底部導覽 |
| backgroundColor | 背景顏色 |
| floatingActionButton | 浮動按鈕 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void main() {
runApp(MaterialApp(
title: 'Flutter Base',
theme: ThemeData(scaffoldBackgroundColor: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text('AppBar'),
),
body: Container(
child: Center(
child: Text('Body'),
),
),
bottomNavigationBar: Container(
height: 50,
child: Center(
child: Text('Bottom Navigation Bar'),
),
),
),
));
}

StatelessWidget
不會改變的靜態頁面,繼承StatelessWidget,並實作build()方法。
快速鍵,輸入stateless

把上面MaterialApp(…)全複製到build()方法中的return 後面。
在runApp()參數設成MainPage(自訂類別名)。
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
30
31
32
33
34
import 'package:flutter/material.dart';
void main() {
runApp(MainPage());
}
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Base',
theme: ThemeData(scaffoldBackgroundColor: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text('AppBar'),
),
body: Container(
child: Center(
child: Text('Body'),
),
),
bottomNavigationBar: Container(
color: Colors.amber,
height: 50,
child: Center(
child: Text('Bottom Navigation Bar'),
),
),
),
);
}
}
StatefulWidget
若畫面有Click按鈕,有互動,會影嚮畫面變化,要繼承StatefulWidget。
快速鍵,輸入stateful

建立二個類別,分別繼承StatefulWidget、State,步驟如下:
- 供外部讀取,繼承StatefulWidget
- 供內部私有使用,繼承 State<供外部讀取的類別名>供外部讀取的類別名>
- 把會變動的內容,寫在_MainPageState類別,build()方法。
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import 'package:flutter/material.dart';
void main() {
runApp(MainPage());
}
class MainPage extends StatefulWidget {
MainPage({Key? key}) : super(key: key);
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int count = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Base',
theme: ThemeData(scaffoldBackgroundColor: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text('AppBar'),
),
body: Container(
child: Row(
children: [
TextButton(
onPressed: () {
setState(() {
count++;
});
},
child: Text("Add"),
),
Text(count.toString()),
TextButton(
onPressed: () {
setState(() {
count--;
});
},
child: Text("Subtract"),
),
],
),
)),
);
}
}

