因此,我试图在此处调用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。但是,没有一种方法可以获取状态代码。我的用例是,当状态代码> 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>
最佳答案
为什么不返回Api Result对象,而不返回包含错误代码和用户的用户?
然后,您可以根据状态代码在FutureBuilder上构建不同的小部件。
关于rest - 当API调用上的响应statusCode> 400时,在Flutter中构建窗口小部件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51018413/