Flutter路由跳转的两种方式

时间:2024-05-05 09:40:26

1.基本路由跳转:文件引入在你要跳转的页面引入

        ElevatedButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (BuildContext context) {
                    return const NewsPage(
                      arguments: {
                        "title": "基本路由新闻页面传值",
                        "aid": 88888888,
                      },
                    );
                  },
                ),
              );
            },
            child: const Text('基本路由跳转新闻页面(传值)'),
          ),

2.命名路由跳转:此时文件在main.dart文件引入

        ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/news', arguments: {
                "title": "命名路由新闻页面传值",
                "aid": 999999999,
              });
            },
            child: const Text('命名路由跳转新闻页面(传值)'),
          ),

此时需要在main.dart页面配置相关属性

import 'package:flutter/material.dart';
import "./pages/namedRoutes/tabs.dart";
import "./pages/namedRoutes/news.dart";
import "./pages/namedRoutes/form.dart";

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

class MyApp extends StatelessWidget {
  // 1.配置路由表
  final Map routes = {
    "/": (context) => const Tabs(),
    "/form": (context) => const FormPage(),
    "/news": (context, {arguments}) => NewsPage(arguments: arguments),
  };
  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Demo",
      debugShowCheckedModeBanner: false, // 去除debug标签
      theme: ThemeData(
        primarySwatch: Colors.blue,
        primaryColor: Colors.red,
      ),
      // home: const Tabs(),
      //2、调用onGenerateRoute处理
      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;
          }
        }
        return null;
      },
    );
  }
}