当前位置:   article > 正文

Flutter路由跳转的两种方式_flutter 路由跳转

flutter 路由跳转

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

  1. ElevatedButton(
  2. onPressed: () {
  3. Navigator.of(context).push(
  4. MaterialPageRoute(
  5. builder: (BuildContext context) {
  6. return const NewsPage(
  7. arguments: {
  8. "title": "基本路由新闻页面传值",
  9. "aid": 88888888,
  10. },
  11. );
  12. },
  13. ),
  14. );
  15. },
  16. child: const Text('基本路由跳转新闻页面(传值)'),
  17. ),

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

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

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

  1. import 'package:flutter/material.dart';
  2. import "./pages/namedRoutes/tabs.dart";
  3. import "./pages/namedRoutes/news.dart";
  4. import "./pages/namedRoutes/form.dart";
  5. void main() {
  6. runApp(MyApp());
  7. }
  8. class MyApp extends StatelessWidget {
  9. // 1.配置路由表
  10. final Map routes = {
  11. "/": (context) => const Tabs(),
  12. "/form": (context) => const FormPage(),
  13. "/news": (context, {arguments}) => NewsPage(arguments: arguments),
  14. };
  15. MyApp({super.key});
  16. @override
  17. Widget build(BuildContext context) {
  18. return MaterialApp(
  19. title: "Flutter Demo",
  20. debugShowCheckedModeBanner: false, // 去除debug标签
  21. theme: ThemeData(
  22. primarySwatch: Colors.blue,
  23. primaryColor: Colors.red,
  24. ),
  25. // home: const Tabs(),
  26. //2、调用onGenerateRoute处理
  27. onGenerateRoute: (RouteSettings settings) {
  28. // 统一处理
  29. final String? name = settings.name;
  30. final Function? pageContentBuilder = routes[name];
  31. if (pageContentBuilder != null) {
  32. if (settings.arguments != null) {
  33. final Route route = MaterialPageRoute(
  34. builder: (context) =>
  35. pageContentBuilder(context, arguments: settings.arguments));
  36. return route;
  37. } else {
  38. final Route route = MaterialPageRoute(
  39. builder: (context) => pageContentBuilder(context));
  40. return route;
  41. }
  42. }
  43. return null;
  44. },
  45. );
  46. }
  47. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/995752
推荐阅读
相关标签
  

闽ICP备14008679号