因爲頁面跳轉須要有多個頁面,因此在項目開始前,須要準備多個頁面,這裏是複用了前面導航項目,而後在pages文件夾下面添加Form.dart和Search.dart兩個文件。app
Search.dartless
import 'package:flutter/material.dart'; class SearchPage extends StatelessWidget { const SearchPage({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar:AppBar( title: Text("搜索頁面"), ) , body: Text("搜索頁面內容區域"), ); } }
首先實現基本的頁面跳轉:在HomPage中點擊按鈕,頁面跳轉到SearchPage。要完成上述過程,須要分三步ide
import 'package:flutter/material.dart'; import '../Search.dart'; class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text("跳轉到搜索頁面"), onPressed: () { //路由跳轉 Navigator.of(context).push( MaterialPageRoute( builder: (context)=>SearchPage() ) ); }, color: Theme.of(context).accentColor, textTheme: ButtonTextTheme.primary ), SizedBox(height: 20), ], ); } }
上面僅僅是實現了頁面跳轉,可是在不少狀況下,頁面跳轉時伴隨着數據傳遞的,下面,實現從CategoryPage跳轉到Form.dart頁面,而且傳遞相關數據。ui
首先須要在CategoryPage頁面中進行頁面跳轉時,寫入須要傳遞的值this
Category.dartspa
import 'package:flutter/material.dart'; import '../Form.dart'; class CategoryPage extends StatefulWidget { CategoryPage({Key key}) : super(key: key); _CategoryPageState createState() => _CategoryPageState(); } class _CategoryPageState extends State<CategoryPage> { @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text("跳轉到表單頁面"), onPressed: (){ Navigator.of(context).push( MaterialPageRoute( builder: (context)=>FormPage(title:'我是跳轉傳值') ) ); }, ) ], ); } }
而後在Form.dart中獲取傳遞過來的值。code
須要注意的是,這裏在獲取頁面跳轉傳值時,不一樣的寫法有着不一樣的做用:orm
這種寫法表明title爲可選傳值,擁有默認值。blog
這種寫法表明title爲必傳參數。事件
Form.dart
import 'package:flutter/material.dart'; class FormPage extends StatelessWidget { String title; FormPage({this.title="表單"}); @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Text('返回'), onPressed: (){ Navigator.of(context).pop(); }, ), appBar: AppBar( title: Text(this.title), ), body: ListView( children: <Widget>[ ListTile( title: Text('我是表單頁面'), ), ListTile( title: Text('我是表單頁面'), ), ListTile( title: Text('我是表單頁面'), ), ListTile( title: Text('我是表單頁面'), ) ], ), ); } }
上面的例子中,還在Form.dart中添加了一個返回路由的按鈕。
代碼下載:點這裏(747f)