flutter 命名路由跳转、传参

无参跳转:
	1、引入要跳转的路由组件
	2、在MaterialApp与home同级
		routes:{ Map类型
			'/路由名':(context)=>组件路由名()
		},
		initialRoute:'/初始路由名'
	3、在回调函数中设置
			
		 跳转:Navigator.pushNamed(context, '/命名路由')
		 
		 替换当前页面: Navigator.of(context).pushReplacementNamed('/路由名');
		 
		 回到根导航栏页面:
		 (1)导入导航栏所在的文件
		 (2)Navigator.of(context).pushAndRemoveUntil( new MaterialPageRoute(builder: (context) => 
		 new 导航栏所在类名()), (route) => route == null );
          	其中:
          	  通过导航栏所在类设置构造函数来接收参数并在类中进行逻辑设置,可指定返回导航栏的哪个路由页面

有参跳转:
	1、引入要跳转的路由组件
	2、在该类中写如下形式的变量来配置路由信息
	    var routes={ //Map类型
	        "/命名路由":(context)=>组件名(),
	        "/命名路由":(context,{arguments})=>组件名(arguments:arguments)
	      };

	3、在MaterialApp与home同级
	
		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; 
	              } 
	            } 
       }
       
     4、在回调函数中:
      	Navigator.pushNamed(context, '/命名路由',arguments: {
               '键名':值
             });
             
     5、命名路由的组件通过构造函数接收参数
        var arguments;
     	类名({this.arguments});
     	this.arguments['键名'] 调用

将有参跳转配置信息封装进文件中,即1、2、3封装

	1、引入要跳转的路由组件
	2、引入
		import 'package:flutter/material.dart';
		
	3、在该文件中写如下形式的变量来配置路由信息
	
	    var routes={ //Map类型
	        "/命名路由":(context)=>组件名(),
	        "/命名路由":(context,{arguments})=>组件名(arguments:arguments)
	      };
		
		var xx=(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; 
	              } 
	            } 
	       };
	       
	4、在main.dart中,MaterialApp
	   onGenerateRoute:xx
	   
	5、参数传递和获取步骤和上面相同

代码示例:
main.dart:

import "package:flutter/material.dart";
import 'page/1.dart';
import 'page/2.dart';
import 'page/3.dart';

import 'page/routes.dart';


void main()
{
  runApp(App());
}

class App extends StatelessWidget{


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Tabs(),
      //默认路由
      initialRoute:'/me' ,
      //路由跳转参数配置
      onGenerateRoute:routeInfo
      );
  }
}
//导航栏和主题都在Scaffold组件中设置
class Tabs extends StatefulWidget {
  final index;
  //回到根导航栏时设置的构造函数
  Tabs({Key key,this.index=0}) : super(key: key);

  @override
  _TabsState createState() => _TabsState(index:this.index);
}

class _TabsState extends State<Tabs> {
  int index=0;
  //将回到根导航栏的参数与页面关联
  _TabsState({this.index=0});
  
  List _page=[Home3(),Home2(),Home4()];
  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text("hh")),
      body:_page[this.index],

      bottomNavigationBar: BottomNavigationBar(
        items:[ 
          BottomNavigationBarItem(//单个bar内容
            icon:Icon(Icons.home),
            title:Text("首页"),
          
          ),
          BottomNavigationBarItem(
            icon:Icon(Icons.category),
            title:Text("第二页"),
            
          ),
          BottomNavigationBarItem(
            icon:Icon(Icons.category),
            title:Text("第三页"),

          )
        ],
        currentIndex: this.index, //选中的底部bar索引
        fixedColor: Colors.green,  //选中的颜色

        onTap:(index){setState(() {
          this.index=index;
        });}, //点击bar回调,必须传入index参数,bar的索引
  
      ),
      );
  }
}


class Home extends StatelessWidget {
  const Home({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          
        ],
      ),
    );
  }
}










封装的配置文件:

import 'package:flutter/material.dart';

import 'me.dart';
import 'search.dart';


var routes={ //Map类型
    "/me":(context)=>Me(),
    "/search":(context,{arguments})=>Search(arguments:arguments)
  };

var routeInfo=(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; 
              } 
            } 
};


跳转的回调函数所在文件:

import 'package:flutter/material.dart';


class Home3 extends StatefulWidget {
  Home3({Key key}) : super(key: key);

  @override
  _Home3State createState() => _Home3State();
}

class _Home3State extends State<Home3> {
  @override
  Widget build(BuildContext context) {
    return Container(
    
       child:Column(
         crossAxisAlignment: CrossAxisAlignment.center,
         mainAxisAlignment: MainAxisAlignment.center,
         
         children: <Widget>[
         
           RaisedButton(child: Text("跳到search"),
              color:Theme.of(context).accentColor,
              onPressed:(){
              //跳转、跳转传参数
                // Navigator.pushNamed(context, '/search');
                 Navigator.pushNamed(context, '/search',arguments: {
                   'id':"12344哈哈"
                 });

              }
           ),
          
          SizedBox(height: 20,),

         ],
       ),
    );
  }
}

接收路由参数组件:

import 'package:flutter/material.dart';

class Search extends StatelessWidget {
  var arguments;
  //接收参数
  Search({this.arguments});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Text('返回'),
        onPressed: (){
          Navigator.of(context).pop();
        },
      ),
      appBar: AppBar(title:Text("search")),
      body:Home(arguments: this.arguments)
    );
  }
}

class Home extends StatelessWidget {
  var arguments;
  Home({this.arguments});
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("参数${this.arguments['id']}")
    );
  }
}

回到导航栏组件:

import 'package:flutter/material.dart';

import '../main.dart';

class Me2 extends StatefulWidget {
  String title='me';


  @override
  _Home2State createState() => _Home2State();
}

class _Home2State extends State<Me2> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text('me-son'),),
        body: Home(),
    );
  }
}

class Home extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text('me-sonnnnn'),
          
          RaisedButton(
            color: Theme.of(context).accentColor,
            child: Text('回到根'),
            onPressed: (){
            //回到根导航栏,导航栏的类设置了构造函数接收参数,并将参数与页面关联
              Navigator.of(context).pushAndRemoveUntil( new MaterialPageRoute(builder: (context) => new Tabs(index: 2)), 
              (route) => route == null );
            },
          )
        ],
      )
    );
  }
}

你可能感兴趣的:(flutter,flutter)