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。

相关推荐
君蓦12 小时前
Flutter 本地存储与数据库的使用和优化
flutter
problc1 天前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
lqj_本人1 天前
鸿蒙next选择 Flutter 开发跨平台应用的原因
flutter·华为·harmonyos
lqj_本人1 天前
Flutter&鸿蒙next 状态管理框架对比分析
flutter·华为·harmonyos
起司锅仔2 天前
Flutter启动流程(2)
flutter
hello world smile2 天前
最全的Flutter中pubspec.yaml及其yaml 语法的使用说明
android·前端·javascript·flutter·dart·yaml·pubspec.yaml
lqj_本人2 天前
Flutter 的 Widget 概述与常用 Widgets 与鸿蒙 Next 的对比
flutter·harmonyos
iFlyCai2 天前
极简实现酷炫动效:Flutter隐式动画指南第二篇之一些酷炫的隐式动画效果
flutter
lqj_本人2 天前
Flutter&鸿蒙next 中使用 MobX 进行状态管理
flutter·华为·harmonyos