1

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;
  }
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
  • There is no supported way to do that. `login` should be made asynchronous (and its callers, and so on). – jamesdlin Dec 06 '21 at 01:06
  • That's exactly the problem. I CANNOT make login async. Much less its callers, and so on... Q: Maybe Flutter has a class that can make an HTTP "post" synchronously? – FoggyDay Dec 06 '21 at 03:16
  • If you can't make `login` properly asynchronous (why not?) then you instead will need to provide a separate API for callers to check (and possibly be notified) when the query is complete. – jamesdlin Dec 06 '21 at 04:47

1 Answers1

-1

Mark login method as async method:

Future<bool> login(String username, String password) async {
  await _queryServer(username, password);
  return _isAuthorized;
}
聂超群
  • 1,659
  • 6
  • 14
  • That's exactly what I CANNOT do. I'm looking for a way to call an async library function without "polluting" the entire call hierarchy with async. – FoggyDay Dec 06 '21 at 03:15