如何处理http服务器端验证错误

问题描述 投票:2回答:1

我试图在登录表单上显示服务器端错误。我想在数据可用时改变状态。但它不起作用。任何人都可以帮忙

或者有更好的方法来做到这一点。

 Future<dynamic> apiRequest(map) async {
    String url = 'https://localhost/api/login';
    var response = await http.post(Uri.encodeFull(url),
        body: map, headers: {"Accept": "application/json"});
    var res = json.decode(response.body);
    return res;
  }

 void _submit() async {
    if (this._formKey.currentState.validate()) {
      _formKey.currentState.save(); // Save our form now.

 var map = {
        'email_id': '',
        'password': '',
      };
      var hello = await apiRequest(map);

     setState(() {
       email_id_error = hello["errors"]["email_id"];
      });

    } else {
      setState(() {
        _autovalidate = true;
      });
    }
  }

 new Text(email_id_error),

来自服务器的响应

{status_code: 4003, errors: {password: [can't be blank], email_id: [can't be blank]}}
http dart flutter
1个回答
0
投票

你可以试试这个

void _submit() async {
    if (this._formKey.currentState.validate()) {
      _formKey.currentState.save(); // Save our form now.
     var map = {
        'email_id': '',
        'password': '',
      };
      var hello = await apiRequest(map);
      if(hello.statusCode ==4003){
        setState(() {
           email_id_error = hello.responseBody["errors"]["email_id"];
        });
      }    
    } else {
      setState(() {
        _autovalidate = true;
      });
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.