英文:
why the function in flutter calling infinitely?
问题
我是Flutter新手。我在点击按钮时调用登录API。API代码写在下面的一个函数中。
我的问题是,点击按钮后,这个函数无限调用,一次只能调用一次。
Future<Login?> logins() async {
print("login function called");
String uemail = emailText.text;
String upassword = passwordText.text;
print("Email: $uemail, Pass: $upassword");
if (uemail.isEmpty || uemail == null) {
print('enter your email');
} else if (upassword.isEmpty || upassword == null) {
print('enter your password');
} else {
Uri myUri = Uri.parse("http://192.168.29.248:5000/login");
var json_body = {'email': uemail, 'password': upassword};
var response = await http.post(myUri, body: json_body);
print('response code ' + response.statusCode.toString());
if (response.statusCode == 200) {
var res = json.decode(response.body);
print('response res' + res.toString());
login = Login.fromJson(res);
if (login?.success == 0) {
print('enter email');
} else if (login?.success == 2) {
print('enter password');
} else if (login?.success == 1) {
print('login success');
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
}
}
return logins();
}
}
请查看我的代码并提供解决方案。
英文:
I'm new in flutter. I'm calling a login API on button click. The API code is written in a function which is below.
My problem is that this function is calling infinitely after clicking on button at a time only.
Future<Login?> logins() async {
print("login function called");
String uemail = emailText.text;
String upassword = passwordText.text;
print("Email: $uemail, Pass: $upassword");
if (uemail.isEmpty || uemail == null) {
print('enter your email');
} else if (upassword.isEmpty || upassword == null) {
print('enter your password');
} else {
Uri myUri = Uri.parse("http://192.168.29.248:5000/login");
var json_body = {'email': uemail, 'password': upassword};
var response = await http.post(myUri, body: json_body);
print('response code ' + response.statusCode.toString());
if (response.statusCode == 200) {
var res = json.decode(response.body);
print('response res' + res.toString());
login = Login.fromJson(res);
if (login?.success == 0) {
print('enter email');
} else if (login?.success == 2) {
print('enter password');
} else if (login?.success == 1) {
print('login success');
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
}
}
return logins();
}
}
Please view my code and provide the solution.
答案1
得分: 0
因为您正在调用函数 return logins();
这被称为递归函数。
根据您的代码,它将是
return login;
英文:
Because you are retuning(calling) the function return logins();
It is known as recursive function.
based on your code it will be
return login;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论