Flutter路由的几种用法

Flutter路由跳转

基本路由跳转

Dart 复制代码
ElevatedButton(
  onPressed: () {
    //基本路由跳转
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return const SearchPage();
      }),
    );
  },
  child: const Text("基本路由跳转"),
),

search.dart页面

Dart 复制代码
import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  final String context;
  final int aid;

  const SearchPage({
    super.key,
    this.context = "",
    this.aid = 0,
  });

  @override
  State<SearchPage> createState() => _SearchPageStateState();
}

class _SearchPageStateState extends State<SearchPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //返回到上一页路由
          Navigator.pop(context);
        },
        child: const Icon(Icons.close),
      ),
      appBar: AppBar(
        title: const Text("搜索页面"),
      ),
      body: Center(
        child: Text(
          "${widget.context} "
          "${widget.aid == 0 ? "" : ",代号:${widget.aid}"}"
        ),
      ),
    );
  }
}

返回上一页路由

Dart 复制代码
Navigator.pop(context);

基本路由跳转传参

Dart 复制代码
ElevatedButton(
  onPressed: () {
    //基本路由跳转传参
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return const SearchPage(
            context: "首页传过来的参数", aid: 123456);
      }),
    );
  },
  child: const Text("基本路由跳转传参"),
),

命名路由跳转

Dart 复制代码
ElevatedButton(
  onPressed: () {
    //命名路由跳转
    Navigator.pushNamed(context, "/search");
  },
  child: const Text("命名路由跳转"),
),

命名路由跳转需要先配置路由

routers.dart配置文件

Dart 复制代码
import 'package:flutter/material.dart';
import 'package:flutter_demo/form.dart';
import 'package:flutter_demo/register2.dart';
import 'package:flutter_demo/search.dart';

//配置路由
Map routes = {
  "/search": (context) => const SearchPage(),
  "/register2": (context) => const Register2(),
  "/form": (context, {arguments}) => FormPage(arguments: arguments),
};

//配置onGenerateRoute固定写法,这个方法相当于一个中间件,可以做权限判断
var 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;
};

然后需要在首页添加initialRoute和onGenerateRoute配置

Dart 复制代码
import 'package:flutter_demo/routers/routers.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //隐藏DEBUG图标
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const Scaffold(
        body: MyHomePage(),
      ),
      initialRoute: "/",
      onGenerateRoute: onGenerateRoute,
    );
  }
}

命名路由跳转传参

Dart 复制代码
ElevatedButton(
  onPressed: () {
    //命名路由传参
    Navigator.pushNamed(
      context,
      "/form",
      arguments: {
        "aid": 123456,
        "name": "张三",
        "age": "18",
      },
    );
  },
  child: const Text("命名路由传参"),
),

context属性中写配置中的路径,arguments属性中是跳转需要带的参数,跳转到form.dart页面并接收参数。

Dart 复制代码
import 'package:flutter/material.dart';

class FormPage extends StatefulWidget {
  final Map arguments;

  const FormPage({
    super.key,
    required this.arguments,
  });

  @override
  State<FormPage> createState() => _FormPageStateState();
}

class _FormPageStateState extends State<FormPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("表单页面"),
      ),
      body: Center(
        child: Text(
          widget.arguments.isEmpty
              ? ""
              : "我是${widget.arguments["name"]},我${widget.arguments["age"]}了,"
                  "代号:${widget.arguments["aid"]}",
        ),
      ),
    );
  }
}

命名路由替换跳转

Dart 复制代码
Navigator.of(context).pushReplacementNamed("/register2");

命名路由替换跳转用pushReplacementNamed,跳转新页面后本页面被替换掉。

移除所有页面返回到根页面

Dart 复制代码
Navigator.of(context).pushAndRemoveUntil(
    MaterialPageRoute(builder: (BuildContext context) {
  return const MyApp();
}), (route) => false);

移除所有页面并返回到指定页面用pushAndRemoveUntil。

相关推荐
sunly_3 小时前
Flutter:启动屏逻辑处理01:修改默认APP启动图标
flutter
sunly_3 小时前
Flutter:启动屏逻辑处理02:启动页
android·javascript·flutter
Alex_z08973 小时前
flutter gradle版本更新到8.9
flutter
那年星空5 小时前
Flutter 设计模式全面解析:抽象工厂
flutter·设计模式·架构
林北芒大果9 小时前
【Flutter】搭建Flutter开发环境,安卓开发
android·flutter
SunshineBrother11 小时前
Flutter求职、面试20+面试官总结:Dart篇
android·前端·flutter
李新_1 天前
一文聊聊Flutter多业务混合工程实践
android·flutter
sunly_1 天前
Flutter:flutter_screenutil屏幕适配
前端·javascript·flutter
sunly_2 天前
Flutter:AnimatedPadding动态修改padding
android·flutter
LinXunFeng2 天前
Flutter - 子部件任意位置观察滚动数据
前端·flutter·开源