Flutter-路由2 命名路由 替换路由 以及返回根

main.dart 入口文件

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_01/res/listData.dart';
import 'package:flutter_01/pages/taps/taps.dart';
import 'package:flutter_01/pages/Search.dart';
import 'package:flutter_01/routes/Routes.dart';

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // home:Tabs(),
        initialRoute: '/',     //初始化的时候加载的路由
        onGenerateRoute: onGenerateRoute

    );
  }
}

Routes.dart 路由文件

import 'package:flutter/material.dart';
import 'package:flutter_01/pages/user/Login.dart';
import 'package:flutter_01/pages/user/RegisterFirst.dart';
import 'package:flutter_01/pages/user/RegisterSecond.dart';
import 'package:flutter_01/pages/user/RegisterThird.dart';

import '../pages/taps/taps.dart';
import '../pages/Form.dart';
import '../pages/Search.dart';
import '../pages/Product.dart';
import '../pages/ProductInfo.dart';


//配置路由,定义Map类型的routes,Key为String类型,Value为Function类型
final Map routes={
  '/':(context)=>Tabs(index: 0,),
  '/form':(context)=>FormPage(),
  '/product':(context)=>ProductPage(),
  '/login':(context)=>LoginPage(),
  '/RegisterFirst':(context)=>RegisterFirstPage(),
  '/RegisterSecond':(context)=>RegisterSecondPage(),
  '/RegisterThird':(context)=>RegisterThirdPage(),
  '/productinfo':(context,{arguments})=>ProductInfoPage(arguments:arguments),
  '/search':(context,{arguments})=>SearchPage(arguments:arguments),

};

//固定写法
var onGenerateRoute=(RouteSettings settings) {
  //String? 表示name为可空类型
  final String? name = settings.name;
  //Function? 表示pageContentBuilder为可空类型
  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;
    }
  }
};

taps.dart 底部菜单

import 'package:flutter/material.dart';
import 'package:flutter_01/pages/taps/Home.dart';
import 'package:flutter_01/pages/taps/Category.dart';
import 'package:flutter_01/pages/taps/Setting.dart';

class Tabs extends StatefulWidget {
  int index = 0;

  Tabs({this.index = 0});

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

class _TabsState extends State {
  int _currentIndex = 0;

  _TabsState(this._currentIndex);

  List _pageList = [
    HomePage(),
    CategoryPage(),
    SettingPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('TITLE')),
      body: _pageList[this._currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        iconSize: 25,
        //图标的大小
        fixedColor: Colors.red,
        //选中颜色
        type: BottomNavigationBarType.fixed,
        //配置多余4个按钮时候配置
        currentIndex: this._currentIndex,
        onTap: (int index) {
          print(this._currentIndex);
          print(index);

          setState(() {
            this._currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
          BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
          BottomNavigationBarItem(icon: Icon(Icons.settings), label: "设置")
        ],
      ),
    );
  }
}

Home.dart 命名路由 以及传参

import 'package:flutter/material.dart';
import 'package:flutter_01/pages/Search.dart';
import 'Setting.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
            onPressed: () {
              // Navigator.push(context,
              //     MaterialPageRoute(builder: (context) => SearchPage()));
              Navigator.pushNamed(context, '/search', arguments: {
                "title": 'title',
                "value": 'value',
              });
            },
            child: Text('跳转到搜索')),
        ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/product');
              // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              //   return SearchPage(value: "传入参数",title: 'TITLE',);
              // }));
            },
            child: Text('跳转到商品界面'))
      ],
    ));
  }
}

Search.dart 接收参数

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  final arguments;

  SearchPage({this.arguments});

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

class _SearchPageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: Text('返回'),
      ),
      appBar: AppBar(
        title: Text(widget.arguments['title']),
      ),
      body: Text(widget.arguments['value']),
      // body: Text("搜索页面内容区域${arguments != null ? arguments['id'] : '0'}"),
    );
  }
}

Setting.dart



import 'package:flutter/material.dart';

class SettingPage extends StatefulWidget {
   //Flutter2.2.0之后需要注意把Key改为可空类型  {Key? key} 表示Key为可空类型
  SettingPage({Key? key}) : super(key: key);

  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        ListTile(
          title: Text("我是一个文本"),
        ),
         ListTile(
          title: Text("我是一个文本"),
        ),
         ListTile(
          title: Text("我是一个文本"),
        ),
         ListTile(
          title: Text("我是一个文本"),
        ),
        Center(
          child: Column(
            children: [
              ElevatedButton(onPressed: (){
                Navigator.pushNamed(context, '/login');
              }, child: Text('跳转登录页面')),
              ElevatedButton(onPressed: (){
                Navigator.pushNamed(context, '/RegisterFirst');
              }, child: Text('跳转注册页面')),
            ],
          ),
        )
      ],
    );
  }
}

RegisterFirst.dart 替换路由(感觉没什么用)

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RegisterFirstPage extends StatelessWidget {
    //Flutter2.2.0之后需要注意把Key改为可空类型  {Key? key} 表示key为可空类型
  const RegisterFirstPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第一步-输入手机号")
      ),
      body:Column(
        children: [
          SizedBox(height: 40),
          Text("这是注册的第一步,请输入您的手机号 然后点击下一步"),
          SizedBox(height: 40),
          ElevatedButton(
            child: Text('下一步'),
            onPressed: (){
                //跳转路由
                Navigator.pushNamed(context, '/RegisterSecond');
                
                //替换路由
                // Navigator.of(context).pushReplacementNamed('/RegisterSecond');
            },
          )
        ],
      )
    );
  }
}

RegisterThird.dart 这里是重点就是 有个返回根方法 可以指定返回 哪个根

Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder:(context)=>new Tabs(index:1)),
(route) => route==null);

import 'package:flutter/material.dart';
import 'package:flutter_01/pages/taps/taps.dart';

class RegisterThirdPage extends StatelessWidget {
  //Flutter2.2.0之后需要注意把Key改为可空类型  {Key? key} 表示key为可空类型
  const RegisterThirdPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第三步-完成注册")
      ),body:Center(
        child: Column(
        children: [
          SizedBox(height: 40),
          Text("输入密码完成注册"),
          SizedBox(height: 40),
          ElevatedButton(
            child: Text('确定'),
            onPressed: (){              
                // Navigator.of(context).pop();
              Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder:(context)=>new Tabs(index:1)),
                      (route) => route==null);

            },
          )
        ],
      ),
      )
    );
  }
}

你可能感兴趣的:(Flutter-路由2 命名路由 替换路由 以及返回根)