一、配置路由文件Routes.dartapp
import 'package:flutter/material.dart'; import '../pages/Tabs.dart'; import '../pages/Form.dart'; import '../pages/Search.dart';//配置路由 final routes={ '/':(context)=>Tabs(), '/form':(context)=>FormPage(),
'/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引入Routes.dartless
import 'Routes.dart路徑'ide
import 'package:flutter/material.dart'; import 'routes/Routes.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( // home:Tabs(), initialRoute: '/', //初始化的時候加載的路由 onGenerateRoute: onGenerateRoute ); } }
路由傳參初頁面ui
import 'package:flutter/material.dart'; class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text("跳轉到搜索頁面"), onPressed: () { //路由跳轉 Navigator.pushNamed(context, '/search',arguments: { "id":123 }); }, color: Theme.of(context).accentColor, textTheme: ButtonTextTheme.primary ), ], ); } }
接收參數頁面this
import 'package:flutter/material.dart'; class SearchPage extends StatelessWidget { //接收頁面參數 final arguments; SearchPage({this.arguments}); @override Widget build(BuildContext context) { return Scaffold( appBar:AppBar( title: Text("搜索頁面"), ) , body: Text("搜索頁面內容區域${arguments != null ? arguments['id'] : '0'}"), ); } }