Flutter路由跳转传值
一、关于Flutter 中的路由配置
Flutter中给我们提供了两种配置路由跳转的方式:1、基本路由 2、命名路由
也就是说Flutter中要实现路由跳转传值的话可以通过两种方式: 一、Flutter 中的基本路由跳转传值 二、Flutter 中命名路由跳转传值
一、Flutter 中的基本路由跳转传值
比如我们现在想从HomePage组件跳转到SearchPage组件传值。 1、需要在HomPage中引入SearchPage.dart
import '../SearchPage.dart';
2、在HomePage中通过下面方法跳转传值
RaisedButton(
child: Text("跳转到搜索页面"),
onPressed: (){
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context){
return SearchPage(title:"表单"); //传值
}
)
);
},
color: Theme.of(context).accentColor,
textTheme: ButtonTextTheme.primary
)
二、Flutter 中命名路由跳转传值
官方文档:https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments
1、Flutter 中的命名路由跳转传值配置路由:
import 'package:flutter/material.dart';
import 'pages/Tabs.dart';
import 'pages/Search.dart';
import 'pages/Form.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final Map<String,Function> routes = {
'/': (contxt) => Tabs(),
'/search': (contxt) => SearchPage(),
'/form': (context, {arguments}) => FormPage(arguments: arguments),
};
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Tabs(),
onGenerateRoute: (RouteSettings settings) {
// 统一处理
final String? name = settings.name;
final Function? pageContentBuilder = this.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;
}
}
});
}
}
2、通过Navigator.pushNamed跳转传值
RaisedButton(
child: Text("跳转到表单演示页面"),
onPressed: (){
Navigator.pushNamed(context, '/form',arguments: {
"id":20
});
},
color: Theme.of(context).accentColor,
textTheme: ButtonTextTheme.primary
)
3、arguments接收参数
import 'package:flutter/material.dart';
class FormPage extends StatelessWidget {
final Map arguments;
FormPage({this.arguments});
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("搜索"),
),
body:Text("我是一个表单页面 ${arguments != null ? arguments['id'] : '0'}")
);
}
}