Flutter:登录名/ http请求

时间:2018-08-29 09:47:12

标签: http dart flutter

我正在尝试使用用户名和密码的textformfields进行登录屏幕,在该屏幕中,当我按下登录按钮时,它将向服务器发出一个http请求,以尝试检索用户数据,如果一切正常,它导航到第二个屏幕,但是,如果没有显示错误。我有一个问题要显示此错误,我不知道该怎么做!我将到目前为止所做的事情放在上面:

return Scaffold(
    body: new Container(
  margin: EdgeInsets.only(
      left: MediaQuery.of(context).size.width / 10,
      right: MediaQuery.of(context).size.width / 10,
      top: MediaQuery.of(context).size.height / 10),
  child: ListView(
    children: <Widget>[
      Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              new TextFormField(
                decoration: new InputDecoration(
                  prefixIcon: new Icon(Icons.person),
                  hintText: "Insert username",
                ),
                onSaved: (val) => username = val,
                validator: (val) => val.isEmpty ? "Insert username" : null,
              ),
              Padding(
                padding: EdgeInsets.all(10.0),
              ),
              new TextFormField(
                obscureText: true,
                decoration: new InputDecoration(
                  prefixIcon: new Icon(Icons.lock),
                  hintText: "Insert password",
                ),
                onSaved: (val) => password = val,
                validator: (val) => val.isEmpty ? "insert password" : null,
              ),
            ],
          )),
      Padding(
        padding: EdgeInsets.all(20.0),
      ),
      new Container(
        margin: EdgeInsets.only(
            left: MediaQuery.of(context).size.width / 4,
            right: MediaQuery.of(context).size.width / 4),
        decoration: new BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: FlatButton(
          onPressed: () => validate(),
          child: Text("Login",
              style: new TextStyle(
                color: Colors.white,
                fontSize: 16.0,
              )),
        ),
      )
    ],
  ),
));}
  validate()async {

final FormState form = _formKey.currentState;

if (form.validate()){
  form.save();
  form.reset();



  var user = await login(username, password);
  if (user != null){

    Navigator.of(context).pushNamedAndRemoveUntil('/secondPage', ModalRoute.withName('/secondPage'));

  }

}}

2 个答案:

答案 0 :(得分:0)

好的,我想办法。在登录功能中,我写道:

if (response.statusCode == 200){
 return User.fromJson(json.decode(response.body));
}else{
 return showAlertMessage(context, response.statusCode.toString());

}

有更好的方法吗?谢谢!

p.s。在return showAlertMessage(context, response.statusCode.toString());下我也应该写一个throw Exception()吗?

答案 1 :(得分:0)

我认为

最好的方法是返回HTTP响应本身(在登录功能中)。然后在窗口小部件中根据状态代码确定要执行的操作,如果状态代码为4xx,则出现错误并显示错误。您可以根据状态码或response.body定义错误。

或另一种方法是只引发异常并在catch块中处理错误。