Flutter教學目錄持續(xù)更新中
github源代碼持續(xù)更新中
1.新建HomePage頁面
這里我們簡單的先新建一個HomePage頁面,頁面使用AppBar加上一個ListView高镐,代碼如下:
class HomeData {
const HomeData({this.title,this.routerName,this.content});
final String title;
final String content;
final String routerName;
}
class HomePage extends StatefulWidget {
final List<HomeData> homeDataList = [
HomeData(
title: 'HomePage',
content: 'HomePage',
routerName: 'home_page'),
];
@override
State<StatefulWidget> createState() {
return HomePageState();
}
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter實戰(zhàn)教學'),
),
body: ListView(
padding: EdgeInsets.all(10),
children: widget.homeDataList.map((HomeData homeData) {
return HomeListItem(homeData: homeData);
}).toList(),
),
);
}
}
class HomeListItem extends StatefulWidget {
const HomeListItem({Key key, @required HomeData homeData})
: homeData = homeData,
super(key: key);
final HomeData homeData;
@override
State<StatefulWidget> createState() {
return HomeListItemState();
}
}
class HomeListItemState extends State<HomeListItem> {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 10),
child: RaisedButton(
padding: EdgeInsets.all(10),
child: Column(
children: [
Text(
'${widget.homeData.title}',
style: TextStyle(fontSize: 18),
),
Text(
'${widget.homeData.content}',
style: TextStyle(fontSize: 12),
)
],
),
onPressed: () {
print('${widget.homeData.title}');
if (widget.homeData.routerName != null &&
widget.homeData.routerName.isNotEmpty) {
Navigator.pushNamed(context, widget.homeData.routerName);
}
},
),
);
}
}
這里先不用管這些控件是怎么使用溉旋,有哪些屬性,先跟著學習嫉髓,后面會依次進行詳細介紹
2.配置MaterialApp的home以及配置路由表
2.1在MyApp中MaterialApp的屬性home配置HomePage頁面作為初始頁面
2.2在MyApp中配置我們的路由表
(這里我們先使用命名路由低滩,配置路由表召夹,更多的路由使用方法會在后期路由專題中作詳細介紹)
代碼如下:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// 應(yīng)用程序小部件使用的顏色。
primarySwatch: Colors.blue,
),
//注冊路由表
routes: routerTable,
home: HomePage(),
);
}
final routerTable = {
'home_page': (context) => HomePage(),
}
}
這里需要說明一下跟沒有dart基礎(chǔ)的同學說明一下恕沫,dart語言跟kotlin一樣监憎,可以不寫出對象類型,他可以根據(jù)值自動反出類型婶溯,所以routerTable不用指名類型
3.頁面跳轉(zhuǎn)
Navigator.pushNamed(context, ‘路由名稱’);
這里我們先使用命名路由跳轉(zhuǎn)鲸阔,更多Navigator的使用將在后期詳細介紹
下一章我們開始學習基礎(chǔ)組件的基本使用方法:基礎(chǔ)組件之Container