Flutter 中的基本路由
項(xiàng)目準(zhǔn)備
由于頁面跳轉(zhuǎn)需要有多個(gè)頁面,所以在項(xiàng)目開始前,需要準(zhǔn)備多個(gè)頁面,這里是復(fù)用了前面導(dǎo)航項(xiàng)目,然后在pages文件夾下面添加Form.dart和Search.dart兩個(gè)文件。
Search.dart
import 'package:flutter/material.dart';class SearchPage extends StatelessWidget {const SearchPage({Key key}) : super(key: key);@overrideWidget build(BuildContext context) {return Scaffold(appBar:AppBar(title: Text("搜索頁面"),) ,body: Text("搜索頁面內(nèi)容區(qū)域"),);} }基本路由
首先實(shí)現(xiàn)基本的頁面跳轉(zhuǎn):在HomPage中點(diǎn)擊按鈕,頁面跳轉(zhuǎn)到SearchPage。要完成上述過程,需要分三步
基本路由跳轉(zhuǎn)傳值
上面僅僅是實(shí)現(xiàn)了頁面跳轉(zhuǎn),但是在很多情況下,頁面跳轉(zhuǎn)時(shí)伴隨著數(shù)據(jù)傳遞的,下面,實(shí)現(xiàn)從CategoryPage跳轉(zhuǎn)到Form.dart頁面,并且傳遞相關(guān)數(shù)據(jù)。
首先需要在CategoryPage頁面中進(jìn)行頁面跳轉(zhuǎn)時(shí),寫入需要傳遞的值
Category.dart
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> {@overrideWidget build(BuildContext context) {return Column(crossAxisAlignment: CrossAxisAlignment.start,mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[RaisedButton(child: Text("跳轉(zhuǎn)到表單頁面"),onPressed: (){Navigator.of(context).push(MaterialPageRoute( builder: (context)=>FormPage(title:'我是跳轉(zhuǎn)傳值')));},)],);} }然后在Form.dart中獲取傳遞過來的值。
需要注意的是,這里在獲取頁面跳轉(zhuǎn)傳值時(shí),不同的寫法有著不同的作用:
這種寫法代表title為可選傳值,擁有默認(rèn)值。
?
這種寫法代表title為必傳參數(shù)。
Form.dart
import 'package:flutter/material.dart';class FormPage extends StatelessWidget {String title;FormPage({this.title="表單"});@overrideWidget 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中添加了一個(gè)返回路由的按鈕。
? ?
?代碼下載:點(diǎn)這里(747f)
?
轉(zhuǎn)載于:https://www.cnblogs.com/yuyujuan/p/11001103.html
總結(jié)
以上是生活随笔為你收集整理的Flutter 中的基本路由的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Learn Python the fir
- 下一篇: webform 的路由