Dart (flutter): Http requests seem not to execute

205 views Asked by At

I'm trying to make a simple HTTP-head request within a Future. However, for some reason, the request is not executed. This is my current code:

  Future<int> logIn({
    required String username,
    required String password,
  }) async {
    print("logIn started");
    final base64creds = base64.encode(utf8.encode(username + ":" + password));
    print(base64creds);
    Map<String, String> headers = new HashMap();
    headers.putIfAbsent("credentials", () => base64creds);
    print(headers.toString());
    var response = await http.head(
      Uri.parse("http://localhost:8060/users/validateLogin/"),
      headers: headers,
    );

    print(response.statusCode);

    return response.statusCode;
  }

The console output of the printout looks like this:

logIn started
MTph
{credentials: MTph}

The Future is executed in a try-catch block. This block always ends up in the catch, means the request either fails or is never executed. I can't figure out what I am doing wrong and hope you can help me!

1

There are 1 answers

0
Henrik Steffens On

I have just solved this issue. The problem here war that the repsonse cannot be a var but must be of type http.Response. So the code would look like this:

  Future<int> logIn({
    required String username,
    required String password,
  }) async {
    final base64creds = base64.encode(utf8.encode(username + ":" + password));
    Map<String, String> headers = new HashMap();
    headers.putIfAbsent("credentials", () => base64creds);
    http.Response response = await http.head(
      Uri.parse(
          "https://pius-server-dev.eu-gb.mybluemix.net/users/validateLogin"),
      headers: headers,
    );
    return response.statusCode;
  }