28.2 命名路由的使用及路由参数的传递
1.源代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String result = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
"second":(context) => Second()
},
home: Scaffold(
appBar: AppBar(title: Text("路由的跳转"),),
body: Center(
child: Column(
children: <Widget>[
Builder(builder: (context){
return RaisedButton(
child: Text('打开第二个页面'),
onPressed: (){
Navigator.pushNamed(
context,"second",
arguments: "我是第一个页面的文本").then((e){
setState(() {
result = e;
});
}
);
}
);
},
),
Text(result)
],
)
)
)
);
}
}
class Second extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('第二个页面'),
),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
child: Text('返回上个页面'),
onPressed: () {
Navigator.pop(context,"我是返回给第一个页面的文本");
}
),
Text( ModalRoute.of(context).settings.arguments)
],
)
),
);
}
}
2.解释源代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
//保存pop返回值,以显示文本
String result = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
//注册路由,根据名字跳转
routes: {
"second":(context) => Second()
},
home: Scaffold(
appBar: AppBar(title: Text("路由的跳转"),),
body: Center(
child: Column(
children: <Widget>[
Builder(builder: (context){
return RaisedButton(
child: Text('打开第二个页面'),
onPressed: (){
Navigator.pushNamed(
context,"second",
//传参数过去 arguments 获取pop返回的值 then()
arguments: "我是第一个页面的文本").then((e){
setState(() {
result = e;
});
}
);
}
);
},
),
Text(result)
],
)
)
)
);
}
}
class Second extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('第二个页面'),
),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
child: Text('返回上个页面'),
onPressed: () {
//关闭页面并返回数据给上一个页面
Navigator.pop(context,"我是返回给第一个页面的文本");
}
),
//获取pushName传过来的值
Text( ModalRoute.of(context).settings.arguments)
],
)
),
);
}
}
3.效果图