面试题答案
一键面试参数传递描述
- 定义接收参数的页面:在接收参数的页面构造函数中定义参数,以便接收传递过来的值。
- 在跳转时传递参数:在使用
MaterialPageRoute
进行页面跳转时,将需要传递的参数作为arguments
属性的值传递给目标页面。 - 在目标页面获取参数:在目标页面的
initState
方法或者build
方法中,通过ModalRoute.of(context)?.settings.arguments
获取传递过来的参数。
代码示例
- 定义接收参数的页面
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'),
),
);
}
}
- 进行页面跳转并传递参数
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
页面接收并显示这个参数。