I want to send xmlhttprequest to my server using Dart. I have an html file that can actually make it. Is there some way to run method from html file in dart? Or maybe this code can be rewritten in dart? As a response I get a JSON that contains objects with two fields: name and duration.

// my html file 
<script>

    function createCORSRequest() {
        let xhr = new XMLHttpRequest();


        if ("withCredentials" in xhr) {
            xhr.open('GET', 'http://localhost:8080/sounds', true);
        } else {
            if (typeof XDomainRequest != "undefined") {
                xhr = new XDomainRequest();
                xhr.open('GET', 'http://localhost:8080/sounds');
            } else {
                xhr = null;
            }
        }
        return xhr;
    }

    function makeCorsRequest() {
        var request = createCORSRequest();
        if (!request) {
            alert('CORS not supported');
            return;
        }

// here I get the names of the objects
        request.onload = function () {
            var movies = request.response;
            for (const movie of movies) {
                console.log(movie.movieName)
            }
        };

        request.onerror = function () {
            alert("Request failed");
        };
        request.responseType = 'json';
        request.send();
    }
</script>

Example of JSON I get as a response from my server:

[
  {
    "movieName": "Dog and the main Dogger",
    "duration": "3:30:03"
  },
  {
    "movieName": "Hunger Games",
    "duration": "3:30:03"
  },
  {
    "movieName": "Robot Chicken",
    "duration": "3:30:01"
  },
  {
    "movieName": "Moskovskaya techka",
    "duration": "3:30:03"
  },
  {
    "movieName": "Terminator",
    "duration": "3:30:03"
  }
] 

I want to get the names (movieName field) from the JSON in Dart as it was done in my HTML file.

1 Answers

0
Mattia On

You can use the http package that add the support to XMLRequests with the BrowserClient.

Here is an example:

var browser = BrowserClient();

var response = await browser.get('http://localhost:8080/sounds');

var body = response.body; //Here you can use 'json.encode' from the `dart:convert` package to parse the json list.