Simon Lowther
Simon Lowther

Reputation: 21

Dart can not use a response.body as a String

long time listener first time caller.

I make an http request to an API, get a response which I convert to a String variable, which is then used in a subsequent http request however the second request fails.

In tracking the error of my ways I replaced the String variable with an actual string identical to the variable and it works. I got the API to echo back the string it is receiving and it echos back the String that should work as a variable.

here is the PHP function

elseif($_POST['action']=='get_defects'){
    $data = get_aircraft_by_token($_POST['token']);
    echo $data['Defects'];
}

here is the Dart function

Map<String, String> _getDefects = {
        'action': 'get_defects',
        'token': _token,
      };
      await _getHttpRequest(_getDefects);
      print(_data);
      var parsedJson = jsonDecode(_data) as List;
      Defects._defects =
          parsedJson.map((jsonItem) => DefectItem.fromJson(jsonItem)).toList();
      Defects.saveDefectFile(Defects._defects);
    }
  }

here is the _getHttpRequest function called...

_getHttpRequest(Map<String, String> _httpRequest) async {
    http.Response _response;
    String _url = 'https://aircraftdata.flexihubs.com/API/interface.php';
    Map<String, String> _header = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    _response = await http.post(_url, headers: _header, body: _httpRequest);
    _data = _response.body;
  }

if I replace

 _token = response.body //does not work, response.body=='token'(true)

with

_token = 'token'; //this works no problem

it works? Printing response.body yields 'token', and echoing it yields 'token'; so I am guessing that there is something about the way the encoding works that I do not know, or something else?

Upvotes: 0

Views: 976

Answers (1)

Simon Lowther
Simon Lowther

Reputation: 21

Found the issue, thanks to the clue in the comments from Ro.

Solved with String.trim();

I guess there must have been a hidden trailing space that I was unaware of?

Upvotes: 1

Related Questions