Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use Future/Async function in a loop? (dart/flutter)

        String random_username ;
        bool available = false;
        int n = 0;
        do{
          random_username = SuperHero.random()+(n.toString());
          n = n+1;
          print(random_username);
          checkUsernameAvailable(random_username).then((value){
            available = value;
          });
        }while(!available);

What I am trying to do is when a new user is registered in Firebase Auth, I want to create a random username for the user, which can be changed later. this code should generate a username, check if it is already in firebase database. If no, then leave the loop, else add a suffix number and retry. (By mistake I've put the name generator in the loop, so every time it will get a new name, and that's okay for now). The function checkUsernameAvailable return "true" if there's no match, i.e available. and vice versa.

The problem is that the loop continues forever. maybe this is due to the async method ,i.e, checkUsernameAvailable. Please help.

like image 429
Aether Avatar asked Aug 07 '26 22:08

Aether


1 Answers

You can use Future.doWhile() method, which performs an operation repeatedly until it returns false :

Future.doWhile(() async {
  final random_username = SuperHero.random() + (n.toString());
  n = n + 1;
  print(random_username);
  return !(await checkUsernameAvailable(random_username));
});
like image 132
Augustin R Avatar answered Aug 09 '26 13:08

Augustin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!