Aquiko
Aquiko

Reputation: 172

I need to press the button 2 times in order to function (flutter)

I have a problem implementing a login button, when I press it, it will not function at first, but when I press it again (same value fields) it works.

here's my code Button:

 Center(child: RaisedButton(onPressed: (){
                              setState(()  {
                                onPressedLogin(userName.text,password.text);
                              });
                            }

The OnPressedLogin():

void onPressedLogin(String userName,String password) async{
bool isValid = false;
var value = await dataBaseHelper.getUserList();
for(User userOB in value){
  //print(userOB.password+" "+password),
  if(userName == userOB.username && password == userOB.password) {
    isValid = true;
    this.password.clear();
    this.userName.clear();
    inputTextColor = Colors.grey[850];
    invalidCredentials = "";
    print("YES");
    //Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    break;
  }
}
if(!isValid){
  inputTextColor = Colors.red[800];
  invalidCredentials = "Invalid Credentials";
}

Upvotes: 2

Views: 1081

Answers (2)

Mohammed Alfateh
Mohammed Alfateh

Reputation: 3524

You are using a Future but in setState() you are not waiting for it so that's way it work in the second press (the value take time to change).

To make it work with single press you have to a wait the Future to complete before rebuilding, here how:

First change the return type of the function

Future<void> onPressedLogin(String userName,String password)

Then in the RaisedButton

onPressed: () async {
  await onPressedLogin(userName.text,password.text);
  setState(() {});
},

Upvotes: 3

miguelik
miguelik

Reputation: 525

The moment you setState(), the UI will refresh! Probably that's the issue, let me explain:

What you should do is to call your function before setState(), so that the screen is refreshed with the new info.

Center(child: RaisedButton(onPressed: (){
                             onPressedLogin(userName.text,password.text);
                          setState(()  {
                            //Variables that change for the refresh.
                   
                          });
                        }

In your specific case, I don't see the need for SetState() as you are only printing values in log, not changing the UI.

Hope it is helpful.

Upvotes: 1

Related Questions