Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access response code and body by calling a method returning http.Response?

I use the following class (a separate dart file) to provide API services:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Services {
  static Future<http.Response> login(String username, String password) async {
    var url = "https://10.0.2.2:5001/api/Login/LoginSystem";
    Map data = {"Username": username, "Password": password};
    var body = json.encode(data);
    var response = await http.post(Uri.parse(url),
        headers: {
          "content-type": "application/json",
          "accept": "application/json"
        },
        body: body);

    print(response.statusCode);
    print(response.body);
    return response;
  }
}

And I use the following code to call the service function:

onPressed: () {
    var response = Services.login("fa2020", "123");
    if (response.statusCode == 200) {
    showDialog<String>(
    context: context,
    builder: (BuildContext context) =>
    const AlertDialog(
        title: Text("ALert"),
        content: Text(response.body),
        ));
    }
}

My problem is that I cannot access the response.statusCode and response.body in the last code. How can I fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use async-await in onPressed callback as Service.login executes in async manner.

onPressed: () async {
  var response = await Services.login("fa2020", "123");
  // ...
},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading