skip to Main Content

I am trying to retrieve values returned after an API call but I am getting this error message:

The getter ‘body’ isn’t defined for the type ‘StreamedResponse’.
Try importing the library that defines ‘body’, correcting the name to the name of an existing getter, or defining a getter or field named ‘body’.

Here is my code:

loginUser() async{
  try{
    final uri = Uri.parse(API.loginURL);
    var request = http.MultipartRequest('POST', uri);

    //Send Input field data
    request.fields['email'] = emailController.text;
    request.fields['password'] = passwordController.text;

    var response = await request.send();

    if(response.statusCode == 200){
      var resBody = jsonDecode(response.body);
      bool success_flag = resBody['success'];
      print("Login successful!");
    }else{
      print("Login failed!");
    }
  }
  catch(e){
    print(e.toString());
  }
}

It seems the response doesn’t have a body

2

Answers


  1. You need to read the response’s stream and convert it to a String before you attempt to decode it:

    if( response.statusCode == 200) {
       var responseData = await http.Response.fromStream(response);
       var resBody = jsonDecode(responseData.body);
       bool success_flag = resBody['success'];
       print("Login successful: $success_flag");
    } else {
       ...
    

    PS: it’s not recommended to mix coding styles and you have camelCase with snake_case together. Stick to one (if unsuer, use one most popular on the platform)

    Login or Signup to reply.
  2. Use code like below with try and catch blocks

    final uri = Uri.parse(API.loginURL);
    var request = http.MultipartRequest('POST', uri);
    
    request.fields['email'] = emailController.text;
    request.fields['password'] = passwordController.text;
    
    var response = await request.send();
    
    var streamedResponse = await http.Response.fromStream(response);
    
    if (streamedResponse.statusCode == 200) {
      var resBody = jsonDecode(streamedResponse.body);
      bool successFlag = resBody['success'];
      if (successFlag) {
        print("Login successful!");
      } else {
        print("Login failed: ${resBody['message']}");
      }
    } else {
      print("Login failed status code: ${streamedResponse.statusCode}");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search