How to put parametrs in url with queryParamets in GET-request in dart?

Viewed 42

I have an API and I need to put non-optional parametrs in GET-request and I did this:

Future<List<FlightBook>> fetchFlights(int mv_id) async {
   
    String basicAuth =
        'Basic ' + base64Encode(utf8.encode('$username:$password'));
    print(basicAuth);

    final queryParameters = {
     "mv_id" : mv_id,
    };
    
    var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&{$queryParameters}" ),  headers: <String, String>{'authorization': basicAuth});
    var jsonResponse = convert.jsonDecode(response.body) as List;
    return jsonResponse.map((e) => FlightBook.fromJson(e)).toList();
  }

but when I tried to get some data from this I got the blank screen with no values and after that I did request like so and everything works fine:

 'var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&mv_id=1'

How can I put this parametr inside my link if I need not only the first elemnt but all elements?

2 Answers

Let's try out with this

 final queryParameters = {
     "mv_id" : mv_id,
     "fmt" : "json",
    };
    var uri = Uri(scheme: "http", host: "/mylink/getFlights.php", queryParameters:queryParameters );
    var response = await http.get(uri,  headers: <String, String>{'authorization': basicAuth});
    

Your string interpolation is wrong. The $ goes outside the braces.

You could do: "http:/mylink/getFlights.php?fmt=json&${queryParameters}"

But in this case, you don't need the curly braces, so I would do "http:/mylink/getFlights.php?fmt=json&$queryParameters"

I agree with the other response on how to add the query parameters, but wanted to show why your version failed in one case and worked in the other.

Related