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), ), ); } }