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。

相关推荐
张风捷特烈4 小时前
Flutter 伪3D绘制#03 | 轴测投影原理分析
android·flutter·canvas
马拉萨的春天7 小时前
flutter 项目结构目录以及pubspec.ymal等文件描述
flutter
bst@微胖子1 天前
Flutter项目之登录注册功能实现
开发语言·javascript·flutter
小墙程序员1 天前
Flutter 教程(十一)多语言支持
flutter
无知的前端1 天前
Flutter 一文精通Isolate,使用场景以及示例
android·flutter·性能优化
yidahis1 天前
Flutter 运行新建项目也报错?
flutter·trae
木马不在转1 天前
Flutter-权限permission_handler插件配置
flutter
江上清风山间明月1 天前
一周掌握Flutter开发--9. 与原生交互(下)
flutter·交互·原生·methodchannel
GeniuswongAir1 天前
Flutter极速接入IM聊天功能并支持鸿蒙
flutter·华为·harmonyos
sayen1 天前
记录 flutter 文本内容展示过长优化
前端·flutter