MST

星途 面试题库

面试题:Flutter中Navigator组件如何与简单状态管理配合实现页面间数据传递

在Flutter中,假设你有两个页面,一个是登录页面,另一个是主页面。登录页面收集用户输入的用户名和密码,通过Navigator.pushNamed跳转到主页面,并将用户名传递过去在主页面显示。请描述使用简单状态管理(如变量)实现这一过程的具体步骤和关键代码。
41.0万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试
  1. 登录页面
    • 在登录页面创建用于存储用户名和密码的变量,例如:
    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('登录'),
    )
    
  2. 主页面
    • 在主页面接收传递过来的用户名。在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'),
        ),
      );
    }
    
  3. 配置路由
    • MaterialApp中配置路由:
    MaterialApp(
      initialRoute: '/login',
      routes: {
        '/login': (context) => LoginPage(),
        '/home': (context) => HomePage(),
      },
    )