MST

星途 面试题库

面试题:Flutter中MaterialPageRoute如何传递参数

在Flutter开发中,使用MaterialPageRoute从一个页面跳转到另一个页面时,通常需要传递一些参数。请描述如何在MaterialPageRoute中实现参数传递,并给出一个简单的代码示例。
31.3万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

参数传递描述

  1. 定义接收参数的页面:在接收参数的页面构造函数中定义参数,以便接收传递过来的值。
  2. 在跳转时传递参数:在使用 MaterialPageRoute 进行页面跳转时,将需要传递的参数作为 arguments 属性的值传递给目标页面。
  3. 在目标页面获取参数:在目标页面的 initState 方法或者 build 方法中,通过 ModalRoute.of(context)?.settings.arguments 获取传递过来的参数。

代码示例

  1. 定义接收参数的页面
class SecondPage extends StatelessWidget {
  final String parameter;
  SecondPage({required this.parameter});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: Text('Received Parameter: $parameter'),
      ),
    );
  }
}
  1. 进行页面跳转并传递参数
class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to Second Page'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondPage(parameter: 'Hello from First Page'),
              ),
            );
          },
        ),
      ),
    );
  }
}

在上述示例中,FirstPage 页面通过 MaterialPageRoute 跳转到 SecondPage 页面,并传递了一个字符串参数 'Hello from First Page'SecondPage 页面接收并显示这个参数。