'How to use an asynchronous validation function with the flutter_login package
I'm trying to use the flutter_login package. The FlutterLogin widget it provides accepts a userValidator field, which accepts a custom function that should have a return type of String? (null is returned if the username is valid, if not, then an error message e.g. 'invalid username').
The problem is that my validation process involves asynchronous steps (as I have to check with my backend database). So assuming a function body for the userValidator field like so:
static Future<String?> usernameValidator(username) async {
bool validated = await myAPI.validateUsername(username);
if (validated) {
return null;
}
return 'invalid username';
}
This throws an error as the function expects String? and not Future<String?>:
"The argument type 'Future<String?> Function(dynamic)' can't be assigned to the parameter type 'String? Function(String?)?'."
So I tried to workaround the issue of returning a Future by using .then():
static String? usernameValidator(username) {
myAPI.validateUsername(username).then((val) {
if (val) {
return null;
}
return 'invalid username';
});
}
However, it seems that anything returned inside the body of .then() doesn't return from the outside function, i.e. userValidator doesn't actually return 'invalid username'.
I'm sure this must have a trivial solution I'm not seeing, since this is a really popular package and validating usernames and emails must surely require asynchronous processes as long as a backend is involved. What's the solution?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
