面试题答案
一键面试- 登录页面:
- 在登录页面创建用于存储用户名和密码的变量,例如:
String username = ''; String password = '';
- 创建输入框用于用户输入用户名和密码,并将输入的值更新到对应的变量中:
TextField( onChanged: (value) { username = value; }, decoration: InputDecoration(labelText: '用户名'), ), TextField( onChanged: (value) { password = value; }, decoration: InputDecoration(labelText: '密码'), obscureText: true, )
- 创建登录按钮,点击按钮通过
Navigator.pushNamed
跳转到主页面,并传递用户名:
ElevatedButton( onPressed: () { Navigator.pushNamed(context, '/home', arguments: username); }, child: Text('登录'), )
- 主页面:
- 在主页面接收传递过来的用户名。在
initState
方法中获取传递的参数:
late String receivedUsername; @override void initState() { super.initState(); receivedUsername = ModalRoute.of(context)!.settings.arguments as String; }
- 在主页面的
build
方法中显示传递过来的用户名:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('主页面'), ), body: Center( child: Text('欢迎,$receivedUsername'), ), ); }
- 在主页面接收传递过来的用户名。在
- 配置路由:
- 在
MaterialApp
中配置路由:
MaterialApp( initialRoute: '/login', routes: { '/login': (context) => LoginPage(), '/home': (context) => HomePage(), }, )
- 在