【问题标题】:Flutter - Navigate to home page if response status 200Flutter - 如果响应状态为 200,则导航到主页
【发布时间】:2021-07-15 11:57:48
【问题描述】:

如何在函数里面放 Navigator 是可能的吗?如果状态码 = 200,我需要从登录重定向到主页。 当尝试下面的代码得到未定义的名称'context'

signIn(String username, password) async {

  //////

  if(response.statusCode == 200) {
    jsonResponse = json.decode(response.body);
    if(jsonResponse != null) {

      Navigator.pushNamed(context, '/HomePage');
    }
  }
}

将导航器放在这里工作,但如果输入错误的用户名和密码再次重定向到主页

onPressed: () {
  signIn(username.text, password.text);
  Navigator.pushNamed(context, '/HomePage');
},

【问题讨论】:

  • 你不能将你的上下文传递给你的函数吗?导航器不是问题,它是您缺少的上下文
  • @Wapazz 我更新了我的问题,你的解决方案是什么?

标签: flutter


【解决方案1】:

这里有两种解决方案:

首先你可以提供上下文作为参数:

signIn(String username, password, context) async {

  //////

  if(response.statusCode == 200) {
    jsonResponse = json.decode(response.body);
    if(jsonResponse != null) {

      Navigator.pushNamed(context, '/HomePage');
    }
  }
}

第二个选项是仅使用响应代码来委派重定向:

onPressed: () {
  int code = await signIn(username.text, password.text);
  if (code == 200)
     Navigator.pushNamed(context, '/HomePage');
  else
     Navigator.pushNamed(context, '/Login');
},


...

int signIn(String username, password) async {

  //////

  return response.statusCode;
}

【讨论】:

    【解决方案2】:

    你可以将signIn函数移到构建函数中的onPress of Button

    @override
    Widget build(BuildContext context) {
        return Column(
            children: [
                UsernameTextField()
                PasswordTextField()
                SignInButton(
                    onTap: () {
                        await signIn(username, password, contex);
                      },
                    )
             ]
        )
    
    }
    
    signIn(String username, String password, BuildContext context) async {
      if(response.statusCode == 200) {
        jsonResponse = json.decode(response.body);
        if(jsonResponse != null) {
    
          Navigator.pushNamed(context, '/HomePage');
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2021-02-09
      相关资源
      最近更新 更多