Rest 当API调用上的响应状态代码为>;时,在颤振中构建小部件;400
因此,我正在尝试调用RESTAPI进行登录。这是在我的api_services.dart中,我在这里调用应用程序的所有apiRest 当API调用上的响应状态代码为>;时,在颤振中构建小部件;400,rest,dart,flutter,flutter-layout,Rest,Dart,Flutter,Flutter Layout,因此,我正在尝试调用RESTAPI进行登录。这是在我的api_services.dart中,我在这里调用应用程序的所有api api\u服务.dart Future<User> loginUser(String email, String password) async { final response = await http.post(serverOauthUrl+'/token', headers: { HttpHeaders.AUTHORIZATIO
api\u服务.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);
}
或者使用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();
},
);
为什么不返回Api结果对象而不是包含错误代码和用户的用户?
然后,您可以根据状态代码在FutureBuilder上构建不同的小部件 多亏了@Thomas,这个问题才得以解决。实际上,这是一个简单的解决办法 为其他初学者添加代码中的更改:
api\u服务.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;
}
希望它能帮助别人
if(response.statusCode > 400)
return new Text("Error"):</code>
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;
}
final responseJson = json.decode(response.body);
User user = User.fromJson(responseJson);
print(user.userName);