Flutter路由传参
1、普通路由
//main.dart
routes: routes,
// 路由跳转
onTap: () {
// 跳转到任务详情页
Navigator.of(context).pushNamed('taskDetail',
arguments:listViewData[index]);
},
// 接收参数,在Widget中
Text(ModalRoute.of(context).settings.arguments.toString();)
2、路由拦截onGenerateRoute
我想把传过来的参数,放在initState中,初始化一个变量,再以变量为参数发送请求获得数据
void initState() {
super.initState();
_taskTrunk = ModalRoute.of(context).settings.arguments;//报错,不知是何原因?
}
查了下网上的同学们提供的方法onGenerateRoute
// main.dart路由
initialRoute: '/',
// routes: routes,//普通路由时定义的
onGenerateRoute: onGenerateRoute,
// route.dart
//配置路由
import 'package:AGV/view/login_view.dart';
import 'package:AGV/view/mainPage_view.dart';
import 'package:AGV/view/task/taskDetail_view.dart';
import 'package:flutter/material.dart';
import 'package:AGV/view/task/taskAdd_view.dart';
final routes = {
"/": (context, {arguments}) => MainPageView(),
"login": (context, {arguments}) => LoginView(),
"taskAdd": (context, {arguments}) => TaskAddView(),
"taskDetail": (context, {arguments}) => TaskDetailView(arguments: arguments),
};
// 处理参数传递
// ignore: top_level_function_literal_block
var onGenerateRoute = (RouteSettings settings) {
// 获取声明的路由页面函数
// var pageBuilder = routes[settings.name];
final Function pageBuilder = routes[settings.name];
print('********************************');
if (pageBuilder != null) {
if (settings.arguments != null) {
// print(settings.arguments);
final Route route = MaterialPageRoute(
builder: (context) {
//将RouteSettings中的arguments参数取出来,通过构造函数传入
return pageBuilder(context, arguments: settings.arguments);
},
settings: settings,
);
return route;
} else {
return MaterialPageRoute(builder: (context) => pageBuilder(context));
}
}
return MaterialPageRoute(builder: (context) => MainPageView());
};
// 路由跳转
onTap: () {
// 跳转到任务详情页
Navigator.of(context).pushNamed('taskDetail',
arguments: {'taskData': listViewData[index]});
},
// 接收参数
class TaskDetailView extends StatefulWidget {
TaskDetailView({Key key, this.arguments}) : super(key: key);
final Map arguments;
@override
_TaskDetailViewState createState() => _TaskDetailViewState();
}
class _TaskDetailViewState extends State<TaskDetailView> {
TaskTrunk _taskTrunk;
void initState() {
super.initState();
_taskTrunk = widget.arguments['taskData'];
}