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
To fix this, you need to set the isTaken variable to false in the else statement. You can do this as follows:
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.
You should use setState for that as well. Here’s an updated version of your code:
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.