Hello I have a problem here am a beginner on dart and flutter development and now I stuck here, I have Auth file and login file now the problem is when ever I put credentials even wrong credentials the app still takes me to homepage what am I doing Wrong, here is my code!
import 'package:adlisting/services/Config.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:get/get.dart';
// ignore: unnecessary_import
import 'package:get/get_state_manager/get_state_manager.dart';
class Auth extends GetxController {
login(email, password) {
var url = Uri.parse(Constants().apiUrl "/auth/login");
var input = json.encode({
"email": email,
"password": password,
});
http
.post(url, headers: {"Content-Type": "application/json"}, body: input)
.then((res) {
print(res);
print(res.body);
Get.offAll(() => HomeScreen());
}).catchError((err) {
print(err);
});
}```
CodePudding user response:
try giving condition as - if the response status code is 200 it should move to the homepage else , if the status code is different give it a toast saying wrong credentials
CodePudding user response:
You have to check the response of API first you have to check API is giving 200 response or not like this
class Auth extends GetxController {
login(email, password) {
var url = Uri.parse(Constants().apiUrl "/auth/login");
var input = json.encode({
"email": email,
"password": password,
});
http
.post(
url,
headers: {"Content-Type": "application/json"},
body: input,
)
.then((res) {
print(res);
print(res.body);
if (res.statusCode == 200) {
//this means API is working fine
Get.offAll(() => HomeScreen());
} else {
//show some error
}
}).catchError((err) {
print(err);
});
}
}
now, in 200 response you have to check the success status of API which will be returning from backend like this
{
'success':true or false
}
note: Its not same for all APIs, it can vary API to API you can ask your backend developer
class Auth extends GetxController {
login(email, password) {
var url = Uri.parse(Constants().apiUrl "/auth/login");
var input = json.encode({
"email": email,
"password": password,
});
http
.post(
url,
headers: {"Content-Type": "application/json"},
body: input,
)
.then((res) {
print(res);
print(res.body);
if (res.statusCode == 200) {
//this means API is working fine
if (res.body['success'] == true) {
Get.offAll(() => HomeScreen());
} else {
print("username or password is not correct");
}
} else {
//show some error
}
}).catchError((err) {
print(err);
});
}
}