skip to Main Content

I have a function checkAvailability that changes the state of variable isTaken to true if the condition matches .

checkAvailabiltiy(String text){
      for(var snapshot in allData){
        var name = snapshot['username'].toString().toLowerCase();
        if(text.toLowerCase() == name){
          setState(() {
            isTaken =true;
          });
        } else{
            
    }
      }}

Once the condition matches the variable changes its state . But after that even if the condition doesnt match the variable remains the same . How can i change it back to false.

TextFormField(

                                
                                
                                onChanged: (value) {
                                  // print("${value}hola");

                                  checkAvailabiltiy(value);
                                  print(isTaken);
                                },)

I tried using the setState in the else case but it didnt work.

2

Answers


  1. To fix this, you need to set the isTaken variable to false in the else statement. You can do this as follows:

    checkAvailabiltiy(String text) {
      for (var snapshot in allData) {
        var name = snapshot['username'].toString().toLowerCase();
        if (text.toLowerCase() == name) {
          setState(() {
            isTaken = true;
          });
        } else {
          setState(() {
            isTaken = false;
          });
        }
      }
    }
    
    
    TextFormField(
      onChanged: (value) {
        checkAvailability(value);
        print(isTaken);
      },
    )
    

    This code will check the availability of the username in the onChanged() callback of the TextFormField. If the username is available, the isTaken variable will be set to false. Otherwise, the isTaken variable will be set to true.

    Login or Signup to reply.
  2. You should use setState for that as well. Here’s an updated version of your code:

    checkAvailability(String text) {
      bool isMatched = false; // Add a boolean flag to track if a match is found
    
      for (var snapshot in allData) {
        var name = snapshot['username'].toString().toLowerCase();
        if (text.toLowerCase() == name) {
          setState(() {
            isTaken = true;
          });
          isMatched = true; // Set the flag to true if a match is found
          break; // Exit the loop when a match is found
        }
      }
    
      // Reset isTaken if no match is found
      if (!isMatched) {
        setState(() {
          isTaken = false;
        });
      }
    }
    

    With this code, isTaken will be set to true when a match is found, and it will be set to false if no match is found in the loop. This way, it will correctly reset the state to false when the condition doesn’t match.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search