I've got a Dart class with the synchronous method bool doLogin(String username, String password)
.
doLogin()
calls internal method _queryServer()
, which in turn calls http.Response response = await http.post()
.
"_queryServer()" needs to be async, in order to use "await" (or use ".then()"). "doLogin()" must NOT be async.
Q: How do I structure my code such that doLogin() doesn't return until _queryServer() has a response (or a failure)?
My code looks something like this:
...
Future<void> _queryServer (username, password) async {
final headers = {'Content-Type': 'application/json'};
Map<String, dynamic> logonRequest = {
"username": username,
"password": password
};
String jsonPayload = jsonEncode(logonRequest);
http.Response response = await http.post(
Uri.parse("https://myserver/login"),
headers: headers,
body: jsonPayload,
);
if (response.statusCode == 200) {
_isAuthorized = true;
}
}
...
bool login(String username, String password) {
_queryServer(username, password);
// Q: How do I block until _queryServer() completes?
return _isAuthorized;
}