I am working with a system of Login
. I have two TextField
, one that is usuario
and the other contrasena
. When the button is pressed entrar, the method comes into action OnTap
, which is in a InkWell
:
onTap: () {
valido=false;
if (usuario != null && contrasena != null) {
//chequea con contenga texto en usuario y contrasena
fetchPost(usuario,
contrasena); //fetchPost conecta con la base de datos
if (valido==true){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => menu()),
);
}else {
print('contrase incorrecta');
}
} else {
_showSnackBar();
The variable valido
will take as true
if data was brought from the database, in case it returns []
it is assigned false
, and it should be executed print('contrase incorrecta')
.
Here I leave the method fetchPost
:
Future<List<Usuario>> fetchPost(String a,b) async {
print('espere....');
final response = await http.get ('https://negociodeprueba.000webhostapp.com/DBRemota/wsJSONConsultarCliente.php?usuario=' + a.toString().trim() + '&&contrasena=' + b.toString().trim());
if (response.statusCode == 200) {
print(response.body);
} //LISTADO DE OBJETOS JSON
var datauser = json.decode(response.body);
print(datauser);
if (datauser.toString() != '[]') {
valido = true;
print(valido);
}
}
The problem is that it never enters the conditional if (datauser.toString() != '[]')
found in the fetchPost
. Therefore, it does not warn that the password is incorrect. The same thing happens to me when I leave the fields empty. If I leave the fields empty on the first try, the method _showSnackBar();
works perfectly, but if I fill fields and then empty them, it doesn't run.
Could it be that it fetchPost
takes a long time to execute and cannot assign the value to the variable valido
? Because the method fetchPost
is Async
.
That's right, as you say, you are making an asynchronous request however you don't wait for the result to perform the validation, you need to use
async
andawait
as follows.