Search code examples
apiflutterdartstreamresponse

how to get value from api with flutter


I have fake Api

https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be

and I want to print some data, I used this code

var headers = {
  'Cookie': '__cfduid=d99061ead63f349023a08a33868eb7ef81619925287'
};
var request = http.Request('GET', Uri.parse('https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be'));

request.headers.addAll(headers);

http.StreamedResponse response = await request.send();

if (response.statusCode == 200) {
  print(await response.stream.bytesToString());
}
else {
  print(response.reasonPhrase);
}

and I get this response. I/flutter (17790): {"first_ame":"Miguel","last_name":"Fay","photo":"https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg","email":"[email protected]","title":"Regional Functionality Developer","job_type":"Supervisor","telephone":["567.700.9452","1-701-720-0774 x9918","1-716-687-6317 x670"],"address":{"zip_code":"20909","street":"Myrtis Pines","city":"West Mekhifort","country":"Greece"},"friends":[{"first_name":"Carlie","last_name":"Kilback","email":"[email protected]"},{"first_name":"Clarabelle","last_name":"Runolfsson","email":"[email protected]"}]}

so how to print the first name and zip code?


Solution

  • finally I got this solve by trying again and again,

        var headers = {
          'Cookie': '__cfduid=d99061ead63f349023a08a33868eb7ef81619925287'
        };
        var request = http.Request(
            'GET',
            Uri.parse(
                'https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be'));
    
        request.headers.addAll(headers);
    
        http.StreamedResponse response = await request.send();
    
        if (response.statusCode == 200) {
          var item =
              JsonDecoder().convert("${await response.stream.bytesToString()}");
          print("item $item");
          print("first_ame ${item['first_ame']}");
          return item;
        } else {
          print(response.reasonPhrase);
        }