How do you add query parameters to a Dart http request?

98,387

Solution 1

You'll want to construct a Uri and use that for the request. Something like

final queryParameters = {
  'param1': 'one',
  'param2': 'two',
};
final uri =
    Uri.https('www.myurl.com', '/api/v1/test/${widget.pk}', queryParameters);
final response = await http.get(uri, headers: {
  HttpHeaders.authorizationHeader: 'Token $token',
  HttpHeaders.contentTypeHeader: 'application/json',
});

See https://api.dartlang.org/stable/2.0.0/dart-core/Uri/Uri.https.html

Solution 2

If you dont want to override the scheme of base endpoint url, use the below technique to convert the map to query string and append it to the base endpoint url

var endpointUrl = 'https://www.myurl.com/api/v1/user';
Map<String, String> queryParams = {
  'param1': '1',
  'param2': '2'
};

var headers = {
  HttpHeaders.authorizationHeader: 'Token $token',
  HttpHeaders.contentTypeHeader: 'application/json',
}

String queryString = Uri.parse(queryParameters: queryParams).query;

var requestUrl = endpointUrl + '?' + queryString; // result - https://www.myurl.com/api/v1/user?param1=1&param2=2
var response = await http.get(requestUrl, headers: headers);

Solution 3

this is more simple

final uri = Uri.parse('$baseUrl/v1/endpoint').replace(queryParameters: {
      'page': page,
      'itemsPerPage': itemsPerPage,
    });
final response = await client.get(uri);

Solution 4

Got the same question. The accepted answer won't work if my url is localhost with port like https://localhost:5001. After spending 1 day to search for solution, I come up with Dio library. Following is my solution using Dio:

var _dio = new Dio();
var options = new Options;
options.headers['Authorization'] = 'bearer $token';
options.contentType = 'application/json';
String url = "https://www.myurl.com";
Map<String, String> qParams = {
  'param1': 'one',
  'param2': 'two',
};

var res = await _dio.get(url, options: options, queryParameters: qParams);

Hope this helps.

Solution 5

Use Uri to pass query parameters like.

final String url = "https://www.myurl.com/api/v1/test/${widget.pk}/";

Map<String, String> qParams = {
 'param1': 'one',
 'param2': 'two',
};
Map<String, String> header = {
HttpHeaders.authorizationHeader: "Token $token", 
    HttpHeaders.contentTypeHeader: "application/json"
};

Uri uri = Uri.parse(url);
final finalUri = uri.replace(queryParameters: qParams); //USE THIS

final response = await http.get(
  finalUri,
  headers: header,
);
Share:
98,387

Related videos on Youtube

Peter Birdsall
Author by

Peter Birdsall

Peter Birdsall [email protected] Reliable, creative, adaptive and loyal, possessing technical, managerial and leadership expertise with experience in technology and business systems. Accomplishments include the creation of an Award winning Decision Support implementation and relocation of our Data Center to a managed co-location. Fulfilled business needs by transitioning to various roles and positions, including management and administration of all back office systems across various hardware platforms. Android Full Stack SDK Developer Development Soft Skills: • SDLC, BI • Database Design • AgileWrap • Design system model • Integration • Self / Outsourcing Android Applications - Google Play (exception *): • Otto Carpool • eRideShare Carpool • DP Image Calculator • AceYourExam • WiFi AirWaves • NDA – MyKickStarter • BCM Entry • BCM Website • BCM Regulations * Mobile API Experience: • Google In-App Billing • Google Admob • Material Design • Facebook SDK • RxJava • Retrofit • Google Volley / GSON • Google Analytics • Deep Linking • Cloud Storage • Espresso • Falcon+ • Accessibility Service • Video Streaming • Permissions 6.0 • Map V2 / NFC • EventBus • Dagger2 Professional Experience: Developer – Mobile Ride Sharing, New York, New York 12/14 to 1/17 Published Android proprietary application – Worked with CEO to create 2 Android applications, one for college students and one for the general public. App includes maps with custom markers and window info, geocoding, forward and reverse, custom sms, Material Design implemented in a Model View Controller framework. Sole full stack Android Developer, acclimate the CEO to Android paradigm vs iPhone. Minimal Viable Product (MVP) published on Google Play, ‘Otto Carpooling’, 60+ screens. MVP: https://play.google.com/store/apps/details?id=com.erideshare.erideshare Developer – Highline Residential, Real Estate Brokerage, New York, New York 3/14 to 8/14 Published Android proprietary application - Performed major role in on-site JAD design sessions with CTO, Project Manager and Designer, providing key Android platform guidance in areas of form factor, device support, UI / UX design, backend, database design, best practices for new proprietary Real Estate application. Sole full stack Android Developer, implemented Google In-App Billing, AdMob, Google Analytics, Widgets, Custom Views, Fonts, Content Provider, Volley, 2D / 3D Animation, RESTful, SDLC. MVP: https://play.google.com/store/apps/details?id=com.hlresidential.aceyourexam Webmaster / Android Developer / IT Support IT Consultant – Bergen Chess Mates, Ridgewood, New Jersey 1/09 to present Android applications: BCMWinTD, BCMWebsite, BCM Regulation Assistant and BCM Notation

Updated on July 08, 2022

Comments

  • Peter Birdsall
    Peter Birdsall almost 2 years

    How do you correctly add query parameters to a Dart http get request? I been unable to get my request to respond correctly when trying to append the '?param1=one&param2=two' to my url, yet it works correctly in Postman. Here's the gist of my code:

        final String url = "https://www.myurl.com/api/v1/test/";
        String workingStringInPostman = "https://www.myurl.com/api/v1/test/123/?param1=one&param2=two";
    
        Map<String, String> qParams = {
         'param1': 'one',
         'param2': 'two',
        };
    
    
       var res = await http
          .get(Uri.encodeFull("$url${widget.pk}/"),
          headers: {HttpHeaders.authorizationHeader: "Token $token", 
            HttpHeaders.contentTypeHeader: "application/json"},
    );
    

    The ${widget.pk} is simply a integer value being pass (See the value 123 in the workingStringInPostman variable.

    The qParams is there for connivence, in case a Uri parameter is needed.

    A code example would be welcomed.

  • Peter Birdsall
    Peter Birdsall over 5 years
    The splitting up of the host and path was the answer.
  • Muthu S
    Muthu S almost 5 years
    what is widget.pk here
  • Pablo
    Pablo over 4 years
    for some reason, the application stops after Uri.https like an exception, but without error, it just stops.
  • Tuan van Duong
    Tuan van Duong over 4 years
    Got error if the url is local host with port like localhost:5001.
  • SardorbekR
    SardorbekR over 3 years
    Most simple and best solution)
  • s.j
    s.j over 3 years
    getting this error still - Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. E/flutter (12741): Receiver: null E/flutter (12741): Tried calling: []("BankName")
  • s.j
    s.j over 3 years
    can you suggest any solution?
  • s.j
    s.j about 3 years
    not working for local address define path of api
  • Nate Bosch
    Nate Bosch about 3 years
    To create a URI for a localhost address. Uri.http('localhost:5001', '/api/v1/whatever', {'param1': 'one'}). If you are hitting issues with https and localhost it could be a certificate issue.
  • Ojonugwa Jude Ochalifu
    Ojonugwa Jude Ochalifu almost 3 years
    Unfortunately, this doesn't work anymore. An error is thrown at http.get(requestUrl....) The argument type 'String' can't be assigned to the parameter type 'Uri'.
  • Jaidyn Belbin
    Jaidyn Belbin over 2 years
    @OjonugwaJudeOchalifu just wrap the String in Uri.parse().
  • Stack Underflow
    Stack Underflow over 2 years
    In order to get a response as a List<String>, I had to do _dio.get<List<dynamic>>(...).data.cast<String>();. If somebody knows a better way, feel free to let me know.
  • Stack Underflow
    Stack Underflow over 2 years
    It should be options.headers = {'Authorization': 'bearer $token'};
  • ᴅ ᴇ ʙ ᴊ ᴇᴇ ᴛ
    ᴅ ᴇ ʙ ᴊ ᴇᴇ ᴛ about 2 years
    this is very easy for the HTTP package not for the Dio package.