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

2,980

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));
});
Share:
2,980
Aether
Author by

Aether

Updated on December 22, 2022

Comments

  • Aether
    Aether over 1 year
            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.

    • pskink
      pskink almost 4 years
      check Future.doWhile
  • Aether
    Aether almost 4 years
    Error: A negation operand must have a static type of 'bool'. Try changing the operand to the '!' operator.dart(non_bool_negation_expression). Actually checkUsernameAvailable returns a Future<bool>. is that the problem?
  • Augustin R
    Augustin R almost 4 years
    Answer updated, you need to await for the result as we return its negation.