Flutter中页面通过路由跳转传参主要分两种,一种是通过push()跳转时根据设定的参数进行传参,另一种是通过pop()返回时进行传参。
父级页面向子页面push()传参
假设从A页面跳到B页面可能需要携带参数userName和userAge这两个参数,那么需要在B页面先设置这两个参数名;假设userName必须填而userAge非必需,那么可以通过设置@required其为必填选项:
class PageB extends StatefulWidget { @override final userName; final userAge; const PageB({Key key,@required this.userName,this.userAge}) : super(key: key); _PageBState createState() => _PageBState(); }
在A页面进行传参:
Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context){ return PageB( userName: '灭霸', userAge: '18岁', ); }));
子页面向父级页面pop()传参
pop()传参是当页面B返回到页面A时,页面A通过.then()接收:
Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context){ return PageB( userName: '灭霸', userAge: '18岁', ); })).then((userInfo){ setState(() { backResult = userInfo; }); });
在B页面中直接把需要传的参数放入pop()中即可:
String userInfo = '对不起,用户灭霸已阵亡!'; Navigator.of(context).pop(userInfo);
此时,我们已经完成了两边页面之间的一个交互,看一下最终效果:
最后附上A、B页面源码
pageA页面
import 'package:flutter/material.dart'; import 'package:test_app/page_b.dart'; class PageA extends StatefulWidget { @override _PageAState createState() => _PageAState(); } class _PageAState extends State<PageA> { String backResult; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('pageA',style: TextStyle(color: Colors.white,fontSize: 20),), ), body: Container( alignment: Alignment.center, child: Column( children: <Widget>[ RaisedButton( child: Text('点击跳转B页面并传输用户信息'), onPressed: (){ Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context){ return PageB( userName: '灭霸', userAge: '18岁', ); })).then((userInfo){ setState(() { backResult = userInfo; }); }); }), Text('${backResult}'), ], ), ), ); } }
pageB页面
import 'package:flutter/material.dart'; class PageB extends StatefulWidget { @override final userName; final userAge; const PageB({Key key,@required this.userName,this.userAge}) : super(key: key); _PageBState createState() => _PageBState(); } class _PageBState extends State<PageB> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('pageB',style: TextStyle(color: Colors.white,fontSize: 20),), ), body: Container( alignment: Alignment.center, child: Column( children: <Widget>[ Text('用户名字:${widget.userName}'), Text('用户年龄:${widget.userAge}'), RaisedButton( child: Text('返回页面A并通知灭霸阵亡消息'), onPressed: (){ String userInfo = '对不起,用户灭霸已阵亡!'; Navigator.of(context).pop(userInfo); }), ], ), ), ); } }