'Get Header values from a API response. How do this with dart?

i'm making a e-commerce app with Flutter, but, i have an issue. I want to take data from the header of response, not just the body. I have some difficult to do what a i want, because i got the project in progress. The image bellow is the response with header:

At "X-Paginacao" is the json what i want, but, in my Flutter app, i have an different method to make a request to api:

  static Future httpGET(String url) async {
    try {
      final response = await http.get(Uri.parse(await buildHost() + url), headers: await buildHeader());
      return jsonDecode(response.body);
    } catch(e) {
      print(e);
    }
  }

How i can make this method return me the body and the header of my response?



Solution 1:[1]

The response class that http get has already has an accessor for your headers, you can simply use it:

class MyResponse {
  MyResponse({
    required this.body,
    required this.headers,
  });

  Map<String, dynamic> body;
  Map<String, dynamic> headers;
}

Future<MyResponse> httpGet(String url) async {
  final res = await http.get(Uri.parse(await buildHost() + url), headers: await buildHeader());

  return MyResponse(
    body: (jsonDecode(res.body)) as Map<String, dynamic>,
    headers: (jsonDecode(res.headers)) as Map<String, dynamic>,
  );
}

Now, if you want to read your header's json:

final response = await httpGet(myUrl);

final xPaginacao = jsonDecode(response.headers['X-paginacao']) as Map<String, dynamic>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 h8moss