1、lib目录下创建routes文件夹,并创建routes.dart文件
import 'package:flutter/material.dart';
import '../pages/tabs.dart';
import '../pages//search.dart';
// ios跳转方式
import 'package:flutter/cupertino.dart';
//需要的路由地址
final routes={
'/':(context)=>HomePage(),
'/search':(context,{arguments})=>Search(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 = CupertinoPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
}else{
final Route route = CupertinoPageRoute(
builder: (context) =>
pageContentBuilder(context));
return route;
}
}
};
2、跳转路由时传参
Navigator.pushNamed(context, "/search",arguments: {
"name":"xiaoxi"
});
3、接收参数
import 'package:flutter/material.dart';
class Search extends StatefulWidget {
//声明参数
final arguments;
//初始化arguments
const Search({super.key,this.arguments});
State<Search> createState() => _SearchState();
}
class _SearchState extends State<Search> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//有状态组件中需要使用widget.来拿到参数
title: Text(widget.arguments["name"]),
),
);
}
}