- 首先,在MaterialApp中传递onGenerateRoute(路由跳转触发的事件), 指定起始路由
import 'package:flutter/material.dart';
import 'BottomTabs.dart';
import './router.dart' as router;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
MyApp() {
print(this.routes['/search']);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: router.generateRoute,
initialRoute: '/',
);
}
}
- router.dart中配置好路由的定向, 这个文件由于批量管理路由
import 'package:flutter/material.dart';
import 'pages/Personal/PersonalPage.dart';
import 'pages/Search/SearchPage.dart';
import './HomePage.dart';
Route<dynamic> generateRoute(RouteSettings settings) {
var arguments = settings.arguments;
print(settings.name);
switch (settings.name) {
case '/Search':
return MaterialPageRoute(
builder: (context) => SearchPage(arguments: arguments));
case '/Personal':
return MaterialPageRoute(builder: (context) => PersonalPage());
case '/':
return MaterialPageRoute(builder: (context) => HomePage());
default:
return MaterialPageRoute(builder: (context) => HomePage());
}
}
- HomePage中设置跳转, 跳转到SearchPage页
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 Scaffold(
body: Center(
child: ElevatedButton(
child: Text('跳转至搜索页'),
onPressed: () {
Navigator.pushNamed(context, '/Search',
arguments: {'searchVal': 'aaa'});
},
),
),
);
}
}
- SearchPage页接收参数
import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
final arguments;
const SearchPage({this.arguments});
@override
_SearchPageState createState() => _SearchPageState(
this.arguments != null ? this.arguments['searchVal'] : '0');
}
class _SearchPageState extends State<SearchPage> {
_SearchPageState(this.searchVal);
String searchVal = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('搜索'),
),
body: Column(
children: [
Text(this.searchVal),
FloatingActionButton(
child: Text('点击返回'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
}