How to get return POST API in Flutter
2,257
you should parse the JSON from response.body not the body directly.
Future<User> login(String username, String password) {
return _netUtil.post(LOGIN_URL, body: {
"username": username,
"password": password
}).then((response) {
//check response status, if response status OK
print("Response Status : $res");
if(response.statusCode == 200){
var data = json.decode(response.body);
if(data.length>0){
//Convert your JSON to Model here
}
else{
//Get Your ERROR message's here
var errorMessage = data["error_msg"];
}
}
});
Author by
Vanya Rachel
Updated on December 08, 2022Comments
-
Vanya Rachel over 1 year
I need your help. I've been follow tutorial for POST API from Login App using REST API and SQFLite , but I can't have any return after calling the request. Please correct my code below.
login_presenter.dart
doLogin(String username, String password) { api.callAPI(username, password).then((Post user) { _view.onLoginSuccess(user); }).catchError((Exception error) => _view.onLoginError(error.toString()));}
rest_ds.dart
Future<User> login(String username, String password) { return _netUtil.post(LOGIN_URL, body: { "username": username, "password": password }).then((dynamic res) { print(res.toString()); if(res["error"]) throw new Exception(res["error_msg"]); return new User.map(res["user"]); });
}
second tutorial I'd get from ParsingJSON-Flutter , the error Object.noSuchMethod always point at
_presenter.doLogin(_username, _password);
which mean I don't reach the presenter? Thanks for helping. -
Zanshin over 5 yearsplease add some context to your answer