Flutter - Route传参

2023-11-07

Navigator 组件支持通过使用通用标识符从应用程序的任何地方导航到特定路由。在某些情况下,你可能还希望能够传递参数给特定路由。例如,你希望导航到 /user 路由并携带上用户信息。

在 Flutter 中,你能通过提供额外的 arguments 给 Navigator.pushNamed() 方法方便地完成这个任务。通过使用 ModalRoute.of 方法或 MaterialApp 和 CupertinoApp 构造器中的 onGenerateRoute() 来获取参数。

这个章节讲解的是如何给特定路由传递参数并使用 ModelRoute.of() 和 onGenerateRoute() 来读取参数。

步骤

  1. 定义需要传递的参数
  2. 创建组件来获取参数
  3. 把组件注册到路由表中
  4. 导航到组件
  5. 定义需要传递的参数

首先,定义需要传递给新路由的参数。在这个示例中,传递了两个数据:页面的标题 title 和内容 message。

创建包含 title 和 message 字段的实体类来同时传递这两个数据。

// You can pass any object to the arguments parameter.
// In this example, create a class that contains a customizable
// title and message.
class ScreenArguments {
  final String title;
  final String message;
 
  ScreenArguments(this.title, this.message);
}
  1. 创建组件来获取参数

接着,创建组件,从 ScreenArguments 提取 title 和 message 参数并展示。 为了访问 ScreenArguments ,可以使用 ModalRoute.of() 方法。 这个方法返回的是当前路由及其携带的参数。

// A widget that extracts the necessary arguments from the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';
 
  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;
 
    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}
  1. 把组件注册到路由表中
    然后,在 MaterialApp 的路由表 routes 中增加一个入口。 路由表 routes 会根据路由的名称来决定需要创建哪个路由。
MaterialApp(
  routes: {
    ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
  },     
);
 
  1. 导航到组件
    最后,在用户点击按钮后导航到 ExtractArgumentsScreen 。 在 Navigator.pushNamed() 方法的 arguments 属性里提供需要传递的参数。 随后, ExtractArgumentsScreen 就可以从参数中提取 title 和 message 。
// A button that navigates to a named route. The named route
// extracts the arguments by itself.
RaisedButton(
  child: Text("Navigate to screen that extracts arguments"),
  onPressed: () {
    // When the user taps the button, navigate to the specific route
    // and provide the arguments as part of the RouteSettings.
    Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'This message is extracted in the build method.',
      ),
    );
  },
);

此外,还 可以使用 onGenerateRoute 提取参数
除直接从组件里提取参数,你也可通过 onGenerateRoute() 函数提取参数,然后把参数传递给组件。
onGenerateRoute() 函数会基于给定的 RouteSettings 来创建正确的路由。

MaterialApp(
  // Provide a function to handle named routes. Use this function to
  // identify the named route being pushed, and create the correct
  // screen.
  onGenerateRoute: (settings) {
    // If you push the PassArguments route
    if (settings.name == PassArgumentsScreen.routeName) {
      // Cast the arguments to the correct type: ScreenArguments.
      final ScreenArguments args = settings.arguments;
 
      // Then, extract the required data from the arguments and
      // pass the data to the correct screen.
      return MaterialPageRoute(
        builder: (context) {
          return PassArgumentsScreen(
            title: args.title,
            message: args.message,
          );
        },
      );
    }
  },
);

完整样例

import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Provide a function to handle named routes. Use this function to
      // identify the named route being pushed, and create the correct
      // Screen.
      onGenerateRoute: (settings) {
        // If you push the PassArguments route
        if (settings.name == PassArgumentsScreen.routeName) {
          // Cast the arguments to the correct type: ScreenArguments.
          final ScreenArguments args = settings.arguments;
 
          // Then, extract the required data from the arguments and
          // pass the data to the correct screen.
          return MaterialPageRoute(
            builder: (context) {
              return PassArgumentsScreen(
                title: args.title,
                message: args.message,
              );
            },
          );
        }
      },
      title: 'Navigation with Arguments',
      home: HomeScreen(),
    );
  }
}
 
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // A button that navigates to a named route that. The named route
            // extracts the arguments by itself.
            RaisedButton(
              child: Text("Navigate to screen that extracts arguments"),
              onPressed: () {
                // When the user taps the button, navigate to the specific route
                // and provide the arguments as part of the RouteSettings.
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ExtractArgumentsScreen(),
                    // Pass the arguments as part of the RouteSettings. The
                    // ExtractArgumentScreen reads the arguments from these
                    // settings.
                    settings: RouteSettings(
                      arguments: ScreenArguments(
                        'Extract Arguments Screen',
                        'This message is extracted in the build method.',
                      ),
                    ),
                  ),
                );
              },
            ),
            // A button that navigates to a named route. For this route, extract
            // the arguments in the onGenerateRoute function and pass them
            // to the screen.
            RaisedButton(
              child: Text("Navigate to a named that accepts arguments"),
              onPressed: () {
                // When the user taps the button, navigate to a named route
                // and provide the arguments as an optional parameter.
                Navigator.pushNamed(
                  context,
                  PassArgumentsScreen.routeName,
                  arguments: ScreenArguments(
                    'Accept Arguments Screen',
                    'This message is extracted in the onGenerateRoute function.',
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
 
// A Widget that extracts the necessary arguments from the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';
 
  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;
 
    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}
 
// A Widget that accepts the necessary arguments via the constructor.
class PassArgumentsScreen extends StatelessWidget {
  static const routeName = '/passArguments';
 
  final String title;
  final String message;
 
  // This Widget accepts the arguments as constructor parameters. It does not
  // extract the arguments from the ModalRoute.
  //
  // The arguments are extracted by the onGenerateRoute function provided to the
  // MaterialApp widget.
  const PassArgumentsScreen({
    Key key,
    @required this.title,
    @required this.message,
  }) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Text(message),
      ),
    );
  }
}
 
// You can pass any object to the arguments parameter. In this example,
// create a class that contains both a customizable title and message.
class ScreenArguments {
  final String title;
  final String message;
 
  ScreenArguments(this.title, this.message);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter - Route传参 的相关文章

随机推荐

  • 多linux系统u盘制作,如何制作一个通用的多系统安装U盘六(Linux相关配置)

    linux相关配置 要引导安装linux 需要把相关linuxISO文件中的相关文件复制出来 主要是核心文件 vmlinuz 和初始内存盘 initrd img 以及isolinux cfg配置文件 有以下区别 CentOS5 x RHEL
  • Addressables学习笔记

    文章目录 运行环境 资源引用 AssetReference 属性 AssetReferenceT AssetLabelReference AsyncOperationHandle 属性 Addressables API Instantiat
  • PyTorch-05神经网络与全连接(Logistic Regression、交叉熵、交叉熵来优化一个多分类的问题、全连接层(MLP网络层)、激活函数与GPU加速、测试、Visdom可视化)

    PyTorch 05神经网络与全连接 Logistic Regression逻辑回归 交叉熵 交叉熵来优化一个多分类的问题 全连接层 MLP网络层 激活函数与GPU加速 测试 validation performance Visdom可视化
  • css中设置字体下划线,css如何设置字体下划线

    css设置字体下划线的方法 可以利用text decoration属性来进行设置 如 text decoration underline text decoration属性用于规定添加到文本的修饰 下划线 上划线 删除线等 属性介绍 tex
  • fatal:'origin' does not appear to be a git repository fatal:Could not read from remote repository

    天gitlab中遇到的问题 当 git push origin branch name时遇到报错如下 fatal origin does not appear to be a git repositoryfatal Could not re
  • Spring、SpringBoot、SpringCloud的关系

    Spring Spring框架 是一套为了解决企业应用开发的复杂性而创建的框架 为开发java应用程序提供了全面的基础架构的支持 它提供了依赖注入和 开箱即用 的一些模块 如Spring Mvc Spring Jdbc Spring Sec
  • MNIST识别--使用Numpy实现线性支持向量机(SVM)

    作为经典的机器学习方法 网上有很多调用sklearn库的SVM接口进行手写数字识别的教程 本文主要采用Numpy从零开始实现线性SVM 以帮助读者了解SVM的实现原理 本文不涉及到太多理论性的内容 纯粹只是代码的实现 注释也不多 后面如果时
  • 静态路由与DHCP

    路由器的路由表 r1 show ip route 查看路由表 默认路由表的特点 1 路由表中记录的是网段 2 路由器默认仅具有直连路由 路由查表规则 1 递归查找 2 最长匹配 所有路由器不可达的网段称为未知网段 获取未知网段的方法 1 静
  • 在html5中播放RTSP/RTMP/HLS/HTTP视频流媒体的几种方案,并支持H.265

    经过多年的项目实战和研发经验的积累 总结了一下对于H5视频可视化在视频播放上如何做到无插件H5展示的方法 尤其是契合安防行业的方案 除了HTTP WebSocket类的传输协议 其他是无法通用地传输到浏览器的 所以 如果要做一款通用的H5视
  • PyPy 安装

    目录 前言 1 下载 2 安装 2 1 安装包解压缩 2 2 添加路径至系统变量 3 cmd 调用 4 对比 Python 3 8的界面 总结 前言 提示 这里可以添加本文要记录的大概内容 听说 PyPy 的纯 Python 环境的运行速度
  • mysql查询性能相关

    1 mysql innodb查询与什么因素有关 这张ppt说的相当详细 http tech uc cn wp content uploads 2013 10 MySQL Innodb E9 AB 98 E6 80 A7 E8 83 BD E
  • 【HTML】创建 <h2>-<h6> 标签

    任务描述 本关任务 依次创建 h2 h6 标签 文本内容为创建不同字体大小的标题 查看它们的区别 实现的效果如下 相关知识 第一关已经创建了h1标签 它是干什么的呢 它一般用来创建标题 另外 h2 也用来创建标题 它们有什么区别呢 h1的字
  • 快速掌握正则表达式

    文章目录 限定符 Qualifier 第一个常用限定符 第二个常用限定符 第三个常用限定符 或运算符 字符类 元字符 Meta characters d 数字字符 w 单词字符 空白符 s 任意字符 行首行尾 贪婪与懒惰匹配 Greedy
  • c++设计模式

    C 是一种面向对象的编程语言 支持许多设计模式 以下是几种常见的设计模式 1 单例模式 Singleton Pattern 确保一个类只有一个实例 并提供一个全局访问点 来访问该实例 2 工厂模式 Factory Pattern 定义一个接
  • kafka笔记3--快速部署KRaft版本的kafka3.1.1

    kafka笔记3 快速部署KRaft版本的kafka3 1 1 1 介绍 2 部署测试 2 1 部署 2 2 测试 3 注意事项 4 说明 1 介绍 Apache Kafka Raft 是一种共识协议 它的引入是为了消除 Kafka 对 Z
  • 【Java愚公】gitlab设置中文

    gitlab设置中文 设置步骤 设置完成后效果图 设置步骤 gitlab版本自带了中文语言包 可以通过上述方式直接切换 设置流程说明如下 访问gitlab服务 在用户偏好设置中设置用户语言类别 如下图所示 设置完成后效果图
  • 【STM32】电子时钟(1)

    一直想系统的学习STM32 但是公司的项目主要是电机算法 每天看到头都快炸了 打算仿照手机上的时钟应用写一个电子时钟 因为这个任务的定位是 好吧 就没有定位 主要是边玩边学 也不设时间期限和具体的功能指标 有空了就搞搞 想到了什么就加上去
  • 成功解决Myeclipse2017破解时遇到的crack.bat文件闪退问题

    解决问题 解决Myeclipse2017破解时遇到的crack bat文件闪退问题 解决方法 是环境变量设置有错 1 新建系统环境变量 JAVA HOME D Program Files MyEclipse2017CI7 binary co
  • Linux 音视频开发杂记之一-环境配置使用vscode

    开发环境 开发环境选择window10 Visual Studio Code ubuntu20 64 虚拟机 一Windows 安装 1 安装git for windows 安装过程直接下一步 主要原因是windows OpenSSH在vs
  • Flutter - Route传参

    Navigator 组件支持通过使用通用标识符从应用程序的任何地方导航到特定路由 在某些情况下 你可能还希望能够传递参数给特定路由 例如 你希望导航到 user 路由并携带上用户信息 在 Flutter 中 你能通过提供额外的 argume