Make a http request in dart whith dart:io

Issue

Hey I’m a beginner and I want to interact with an API with dart:io for fetch JSON files I can fetch the data with this code :

  final HttpClient client = HttpClient();
  client.getUrl(Uri.parse("https://api.themoviedb.org/3/movie/76341?api_key=fbe54362add6e62e0e959f0e7662d64e&language=fr"))
  .then((HttpClientRequest request) {
    return request.close();
  })
  .then((HttpClientResponse response) {
    Map a;
    print(a);

But I want to have a Map whith the JSON but I can’t do it. If I could get a String that contains the JSON I could do it with
json.decode();

also know that the answer is stored in an int list that represents the utf8 values of the characters so with utf8.decode(responce.toList()) I can get the utf8 value but responce.toList() return a Future but even if it may be easy I don’t know how to get the list.

Solution

import 'dart:convert';
import 'dart:io';

void main() async {
  final client = HttpClient();
  final request = await client.getUrl(Uri.parse(
      'https://api.themoviedb.org/3/movie/76341?api_key=fbe54362add6e62e0e959f0e7662d64e&language=fr'));
  final response = await request.close();
  final contentAsString = await utf8.decodeStream(response);
  final map = json.decode(contentAsString);
  print(map);
}

Answered By – Alexandre Ardhuin

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *