Flutter路由跳转优雅实现姿态

1.新建一个Router类

import 'package:flutter/material.dart';
import './goods.dart';
import './noFound.dart';
import './detail.dart';

class Router {
  // 路由声明
  static Map routes = {
    '/goods': (context, {arguments}) => Goods(arguments: arguments),
    '/detail': (context) => Detail(),
  };
  static run(RouteSettings settings) {
    final Function pageContentBuilder = Router.routes[settings.name];

    if (pageContentBuilder != null) {
      if (settings.arguments != null) {
        // 传参路由
        return MaterialPageRoute(
            builder: (context) =>
                pageContentBuilder(context, arguments: settings.arguments));
      } else {
        // 无参数路由
        return MaterialPageRoute(
            builder: (context) => pageContentBuilder(context));
      }
    } else {
      // 404页
      return MaterialPageRoute(builder: (context) => NoFoundPage());
    }
  }
}

2.在main入口中使用上述类的run方法

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RestartWidget(
      child: MaterialApp(
        theme: ThemeData(backgroundColor: Colors.transparent),
        // 监听路由跳转
        onGenerateRoute: (RouteSettings settings) {
          return Router.run(settings);
        },
        home: Scaffold(
          body: Page(),
        ),
      ),
    );
  }
}
void main() {
  runApp(MyApp());
}

3.带参路由跳转

import 'package:flutter/material.dart';

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () {
          // 进行Named页面跳转 传递参数
          Navigator.pushNamed(context, '/goods', arguments: {'id': 126});
        },
        child: Text("跳转到"),
      ),
    );
  }
}

4.无参路由跳转

import 'package:flutter/material.dart';

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () {
          // 进行Named页面跳转 传递参数
          Navigator.pushNamed(context, '/detail');
        },
        child: Text("跳转到detail页"),
      ),
    );
  }
}

5.goods.dart

import 'package:flutter/material.dart';

class Goods extends StatelessWidget {
  Goods({this.arguments});
  final Map arguments;

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Text(
            "hi this is next page, id is ${arguments != null ? arguments['id'] : '0'}"),
      ),
    );
  }
}

6.detail.dart

import 'package:flutter/material.dart';

class Detail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () {
          // 进行Named页面跳转 传递参数
          Navigator.pop(context);
        },
        child: Text("返回"),
      ),
    );
  }
}

你可能感兴趣的:(Flutter路由跳转优雅实现姿态)