当 API 调用的响应 statusCode 大于 400 时在 Flutter 中构建小部件

Building widget in Flutter when response statusCode on API call is >400

所以我正在尝试调用 REST API 以在此处登录。这是在我的 api_services.dart 中,我在其中调用应用程序的所有 API。

api_services.dart

Future<User> loginUser(String email, String password) 
async {
    final response = await http.post(serverOauthUrl+'/token',
    headers: {
    HttpHeaders.AUTHORIZATION: "xxxx"
  },
  body: {
     "email":"$email",
     "password":"$password",
  }
);
print(response.statusCode);
final responseJson = json.decode(response.body);
return new User.fromJson(responseJson);
}

我可以通过两种方式在我的 UI 文件中调用此 loginUser() 方法并获得响应。一个使用 then() 方法,另一个使用 FutureBuilder。但是,在方法的none中,是否可以得到状态码。我的用例是,当状态代码>400 时,我将构建一个显示错误消息的小部件。

login_screen.dart

then() 方法代码:

_callLoginAPI(String email, String password){
  loginUser(userName, password, "password").then((response) {
        response.data.token;
       // want my status code here as well along with response data
    }
    else
    {
      //todo show something on error
    }
  }, onError: (error) {
    debugPrint(error.toString());
  });


}

或者使用 FutureBuilder :

return new FutureBuilder<User>(

      future: loginUser(email, password),
      builder: (context, snapshot) {

        if (snapshot.hasData) {
          print(snapshot.data.token);
        } else if (snapshot.hasError) {
          print(snapshot.error);
          return new Text("${snapshot.error}");
        }
        return new CircularProgressIndicator();
      },
    );

我想做的是这样的

if(response.statusCode > 400)
   return new Text("Error"):</code>

为什么您 return 不是一个 Api 结果对象,而是一个包含错误代码和用户的用户? 然后,您可以根据状态代码在 FutureBuilder 上构建不同的小部件。

感谢@Thomas,此问题已解决。实际上是一个简单的解决方案。

在代码中添加更改以供其他初学者遵循:

api_services.dart

Future<http.Response> loginUser(String email, String password) async {
  final response = await http.post(serverOauthUrl+
    '/token',
    headers: {
    HttpHeaders.AUTHORIZATION: "Basic xxx"
    },
    body: {
      "email":"$email",
      "password":"$password",
    }
  );

  return response;
}

因此,我返回的不是用户,而是 http.Response 对象,现在我可以从 UI 文件中检索所有必需的信息。

像这样:

final responseJson = json.decode(response.body);
      User user = User.fromJson(responseJson);
      print(user.userName);

希望对大家有所帮助