Navigator.push 和 Navigator.pop
-
Navigator.push
:是跳轉到下一個頁面,它要接受兩個參數一個是上下文context
,另一個是要跳轉的函數。 -
Navigator.pop
:是返回到上一個頁面,使用時傳遞一個context(上下文)參數,使用時要注意的是,你必須是有上級頁面的,也就是說上級頁面使用了Navigator.push
。
import 'package:flutter/material.dart'; void main (){ runApp( MaterialApp( title:'導航演示1', home:new FirstScreen() ) ); } class FirstScreen extends StatelessWidget{ @override Widget build(BuildContext context){ return new Scaffold( appBar: AppBar( title: Text('導航演示'), ), body: Center( child: RaisedButton( child: Text('詳細頁面', style: TextStyle( color: Colors.black ) ), onPressed: (){ Navigator.push( context, new MaterialPageRoute( builder:(context)=>new SecondScreen() ) ); }, ) ), ); } } class SecondScreen extends StatelessWidget{ @override Widget build(BuildContext context){ return new Scaffold( appBar: AppBar(title: Text('詳細頁面'),), body: Center(child: RaisedButton(child: Text('返回'), onPressed: (){ Navigator.pop(context); }, ),), ); } }
傳遞參數
import 'package:flutter/material.dart'; //申明一個參數 class Product{ final String title; //商品標題 final String decription; //商品描述 Product(this.title,this.decription); } void main(){ runApp( MaterialApp( title: "商品導航", home: ProductList( products:List.generate( 30, (i)=>Product("商品 $i","這是個商品詳情,編號為:$i") ) ) ) ); } class ProductList extends StatelessWidget { //接收參數 final List<Product> products; ProductList({Key key,@required this.products}):super(key:key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('商品列表'), ), body: ListView.builder( itemCount: products.length, itemBuilder: (context,index){ return ListTile( title:Text(products[index].title), onTap: (){ Navigator.push( context, MaterialPageRoute( builder: (context)=>ProductDetail(product:products[index]) ) ); }, ); }, ), ); } } class ProductDetail extends StatelessWidget { final Product product; ProductDetail({Key key,@required this.product}):super(key:key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("${product.title}"), ), body: Center( child: Text(product.decription), ), ); } }