1.計數器實例
//導入Material UI組件庫
import 'package:flutter/material.dart';
//import 'package:english_words/english_words.dart';
//應用程序的入口runApp方法,啓動flutter項目,runApp接收一個Widget參數
void main() {
runApp(MyApp());
}
//根組件,繼承了StatelessWidget類
class MyApp extends StatelessWidget {
//通過build方法構建UI界面
@override
Widget build(BuildContext context) {
//MaterialApp是Material庫中提供的Flutter App框架,自身也是一個Widget
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
//Flutter應用的首頁
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
//首頁Widget,繼承了StatefulWidget類,持有state
class MyHomePage extends StatefulWidget {
//接收上面調用MyHomePage構建函數時傳入的參數title
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
//繼承StatefulWidget類後特有的方法
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//state中存儲的數據
int _counter = 0;
//通過setState改變_counter的值,重新調用build方法構建UI界面
void _incrementCounter() {
setState(() {
_counter++;
});
}
//將build方法挪到State類中
@override
Widget build(BuildContext context) {
//Scaffold是Material庫提供的頁面腳手架,裏面有導航欄、標題和包含主屏幕Widget數的body屬性
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
//將子組件對齊到屏幕中心
body: new Center(
//將子組件按垂直方向排列
child: new Column(
//將子組件居中
mainAxisAlignment: MainAxisAlignment.center,
//存放子組件集合
children: <Widget>[
//Text文本組件
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
//帶“+”的懸浮按鈕
floatingActionButton: new FloatingActionButton(
//點擊時觸發函數
onPressed: _incrementCounter,
tooltip: 'Increment',
//圖標
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
效果:
2.點擊鏈接,跳轉到新路由(頁面)
//創建一個新路由組件
class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("This is new route"),
),
);
}
}
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
... //省略無關代碼
FlatButton(
child: Text("open new route"),
textColor: Colors.blue,
onPressed: () {
//將創建好的新路由push進路由棧
Navigator.push( context,
//構建路由頁面的具體內容,返回值是一個widget
MaterialPageRoute(builder: (context) {
return NewRoute();
}));
},
),
],
)
效果: