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));
});
Author by
Aether
Updated on December 22, 2022Comments
-
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 almost 4 yearscheck
Future.doWhile
-
-
Aether almost 4 yearsError: 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 almost 4 yearsAnswer updated, you need to await for the result as we return its negation.