I'm making a login application using flutter. I wanna log in with the email and password. If the response is 200 it will go to another page and if not it will display "Invalid Credential". My problem is I always get an Invalid Credential even if I enter the correct email and password. I think I have a problem with the token. How can I solve this problem? Here's the response from my postman.
Method: POST->Body->JSON
{
"email": "[email protected]",
"password": "123456"
}
//
{
"code": 0,
"message": "success",
"data": {
"Id": 121106,
"Name": "User 1",
"Email": "[email protected]",
"Token": "55ecaa9b-0a0a-4669-b234-c7e7c88f8f41"
}
}
//
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(10.0),
child: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: emailController,
decoration: const InputDecoration(
labelText: "Email",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email)),
),
const SizedBox(height: 15,),
TextFormField(
controller: passController,
decoration: const InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email)),
),
const SizedBox(height: 15,),
OutlinedButton.icon(onPressed: () {
login();
}, icon: const Icon(Icons.login, size: 18,), label: const Text("Login")),
],
)
)
),
),
);
}
//create function to call login post api
Future<void> login() async {
if(emailController.text.isNotEmpty && passController.text.isNotEmpty) {
var headers = {"Content-type": "application/json"};
var myBody = {'email' : emailController.text, 'password' : passController.text,};
var response = await http.post(Uri.parse("url"),
headers: headers,
body: utf8.encode(json.encode( myBody )));
print(response.statusCode);
print(response.body);
if(response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()));
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Invalid Credentials.")));
}
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Blank Field Not Allowed")));
}
} }
CodePudding user response:
Check the response:
print(response.statusCode);
print(response.body);
Set the correct headers, but what headers are acceptable for the REST endpoint may vary. You need to read the API documentation.
Something like this MIGHT work, but the actual content-type may vary depending on the REST endpoint:
var headers = {"Content-type": "application/json"};
var response = await http.post(Uri.parse("http://restapi.com/api/login"),
headers: headers,
body: ({
'email' : emailController.text,
'password' : passController.text,
}));
Additionally, it might be necessary to encode the body along these lines:
var myBody = {
'email' : emailController.text,
'password' : passController.text,
}
...
body: utf8.encode(json.encode( myBody ))