在lib目录下新建个routes文件夹,里面新建个Routes.dart文件来统一管理我们的路由跳转及传参, 在这里我们就以Home.dart文件跳转到Search.dart文件并传参为例
Routes.dart
代码语言:javascript复制import 'package:flutter/material.dart';
import '../pages/Tabs.dart';
import '../pages/Search.dart'; //需要引入跳转页面地址
// 配置路由
final routes = {
// 前面是自己的命名 后面是加载的方法
'/': (context) => Tabs(), //不用传参的写法
'/search': (context, {arguments}) =>
SearchPage(arguments: arguments), //需要传参的写法
};
// 固定写法,统一处理,无需更改
var onGenerateRoute = (RouteSettings settings) {
final String name = settings.name;
final Function pageContentBuilder = routes[name];
if (pageContentBuilder != null) {
if (settings.arguments != null) {
final Route route = MaterialPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
} else {
final Route route =
MaterialPageRoute(builder: (context) => pageContentBuilder(context));
return route;
}
}
};
还需要在main.dart入口文件进行配置
代码语言:javascript复制import 'package:flutter/material.dart'; //快捷方式:fim
import 'routes/Routes.dart'; //引入配置的路由文件
void main() {
runApp(MyApp());
}
//自定义组件
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
initialRoute: '/', //初始化加载的路由
onGenerateRoute: onGenerateRoute
);
}
}
Home.dart
代码语言:javascript复制import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("跳转到搜索页面"),
onPressed: () {
Navigator.pushNamed(context, '/search',
//在arguments里面带上我们需要传参值
arguments: {"id": 123, "name": "zz"});
},
color: Theme.of(context).accentColor,
textTheme: ButtonTextTheme.primary),
],
);
}
}
Search.dart
代码语言:javascript复制import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
// 接收上个页面的参数
Map arguments;
SearchPage({Key key, this.arguments}) : super(key: key);
@override
//参数传递给下面的类
_SearchPageState createState() => _SearchPageState(arguments: this.arguments);
}
class _SearchPageState extends State<SearchPage> {
Map arguments;
_SearchPageState({this.arguments});
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Text('返回'),
onPressed: () {
Navigator.of(context).pop();
},
),
appBar: AppBar(
title: Text("搜索"),
),
//页面上就显示我们获取上个页面的参数
body: Text("${arguments['id']}${arguments['name']}"));
}
}