Flutter - 如果响应状态为 200

时间:2021-07-15 11:57:48

标签: flutter

怎么把Navigator里面的函数放进去是可能的?如果状态代码 = 200,我需要从登录重定向到主页。 当尝试下面的代码时得到 Undefined name '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');
},

2 个答案:

答案 0 :(得分:2)

这里有两种解决方案:

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

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;
}

答案 1 :(得分:1)

您可以将signIn函数移动到构建函数中的onPress 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');
    }
  }
}