- 定义需要传入参数类(也可以不定义这个类,在通过Navigator.pushName()跳转的时候直接传递参数)
class PassParmasData { final String title; final String message; PassParmasData(this.title,this.message); } - 创建组件来获取参数
import 'package:flutter/material.dart'; class PassDataPage extends StatelessWidget { static const routeName = '/passData'; @override Widget build(BuildContext context) { //通过ModalRoute.of(context).settings.arguments来获取当前路由传递过来的参数 //通过上面定义的类来接收参数 final PassParmasData args = ModalRoute.of(context).settings.arguments; //接收直接通过Navigator.pushName()传递过来的参数 final Map args = ModalRoute.of(context).settings.arguments; return Scaffold( appBar: AppBar( title: Text( //PassParmasData传过来的参数 args.title //直接传递的参数 args["title"] ), ), body: Center( child: Text( args.message ), ), ); } } - 把组件注册到路由表中。在 MaterialApp 的路由表 routes 中增加一个入口,路由表 routes 会根据路由的名称来决定需要创建哪个路由。
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return MaterialApp( title:"hello flutter", home: MyStackPage(), theme: ThemeData( primaryColor: Color(0xffbadc58), highlightColor: Colors.transparent, splashColor: Colors.transparent, ), routes: { '/detail':(context)=>DetailContent('123'), '/search':(context)=>SearchPage(), //在 MaterialApp 的路由表 routes 中增加一个入口,路由表 routes 会根据路由的名称来决定需要创建哪个路由。 PassDataPage.routeName :(context)=> PassDataPage() }, // debugShowCheckedModeBanner: false, ); } }
4.导航到组件。在用户点击按钮后导航到 PassDataPage。在 Navigator.pushNamed() 方法的 arguments 属性里提供需要传递的参数。随后,PassDataPage 就可以从参数中提取 title 和 message
dart RaisedButton( child: Text("通过命名路由跳转到PassDataPage页面并传递参数"), onPressed: (){ Navigator.pushNamed( context, PassDataPage.routeName, //通过第一步定义的类来传递参数 arguments: PassParmasData("这是传递过来的title","这是传递过来的message") //直接传递参数 arguments:{ "title":"这是传递过来的title", "message":"这是传递过来的message" } ); }, )