You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Android应用登录后跳转HomePage报错的解决咨询

Flutter登录后跳转HomePage的正确实现

错误原因分析

你遇到的type 'Future' is not a subtype of type '(() => dynamic)?'错误,大概率是因为错误地将Navigator.push的返回值(Future对象)直接当作回调函数传递(比如直接写onTap: Navigator.of(context).push(...)),而不是将导航逻辑放在异步函数内部执行。

正确实现方式

在signUserIn函数的登录成功分支里,添加导航代码即可。另外建议使用pushReplacement替代push,这样登录后用户无法通过返回键回到登录页,更符合登录流程的逻辑:

修改后的LoginPage关键代码

void signUserIn() async {
  try{
    Response response = await post(
        Uri.parse('https://www.somepage.com/login.php'),
        body: {
          'email' : emailController.text,
          'password' : passwordController.text
        }
    );

    if(response.statusCode == 200){
      var data = jsonDecode(response.body.toString());
      if(data['success'] == 1) {
        print(data['message']);
        
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('email', emailController.text);
        prefs.setString('token', data['token']);

        // 登录成功后跳转至HomePage
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => HomePage())
        );

      } else {
        print(data['status']);
        print(data['message']);
      }
    }else {
      print('Login failed...');
      print(response.statusCode);
    }
  }catch(e){
    print(e.toString());
  }
}

补充:登出逻辑优化

当前HomePage的signUserOut函数只清除了缓存,没有跳转回登录页,建议补充导航代码:

修改后的HomePage关键代码

void signUserOut() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.remove('email');
  prefs.remove('token');
  
  // 登出后跳转回登录页,同样使用pushReplacement
  Navigator.of(context).pushReplacement(
    MaterialPageRoute(builder: (context) => LoginPage())
  );
}

注意事项

  • 确保context在调用Navigator时是可用的:由于LoginPage是StatelessWidget,build方法中的context可以直接在signUserIn中使用,无需额外处理。
  • 如果后续使用命名路由,会让导航逻辑更清晰,示例如下(可选):
    // 在MaterialApp中配置路由
    routes: {
      '/login': (context) => LoginPage(),
      '/home': (context) => HomePage(),
    },
    // 跳转时使用
    Navigator.of(context).pushReplacementNamed('/home');
    

内容的提问来源于stack exchange,提问作者bzc0fq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:37:02