Dart: convert map into query string

Solution 1:

Have you looked at the Uri class in dart:core. You can construct a Uri class from Url components :

new Uri({String scheme, String userInfo: "", String host: "", port: 0, String path, 
  Iterable<String> pathSegments, String query, 
  Map<String, String> queryParameters, fragment: ""}) #

Notice you pass the query string as a map, if you are using a HTTP client that doesn't take this class you can .toString it to get the Url.

I use this in my code rather than string Url's

As an example using your data above :

void main() {

      String eml = "[email protected]";
      String passwd = "password";

      Map json = {
                  "email":  eml,
                  "password": passwd
      };  


      Uri outgoingUri = new Uri(scheme: 'http',
          host: 'localhost',
          port: 8080,
          path: 'myapp',
          queryParameters:json);

      print(outgoingUri);

    }

This prints :

http://localhost:8080/myapp?email=me%40here.com&password=password

Note that once constructed a Uri is immutable, i.e. you can't change the query parameters again. There is also this package in pub which may give more facilities although I've not used it yet.

Solution 2:

TL;DR

String queryString = Uri(queryParameters: {'x': '1', 'y': '2'}).query;

print(queryString); // x=1&y=2

Solution 3:

final yourMap = {'x': '1', 'y': '2'};
final queryString = yourMap.toMap().entries.map((e) => '${e.key}=${e.value}').join('&');
print(queryString); // x=1&y=2

Solution 4:

i wrote a recursive function to turn any Map<String, dynamic> to query String.

String getQueryString(Map params, {String prefix: '&', bool inRecursion: false}) {

    String query = '';

    params.forEach((key, value) {

        if (inRecursion) {
            key = '[$key]';
        }

        if (value is String || value is int || value is double || value is bool) {
            query += '$prefix$key=$value';
        } else if (value is List || value is Map) {
            if (value is List) value = value.asMap();
            value.forEach((k, v) {
                query += getQueryString({k: v}, prefix: '$prefix$key', inRecursion: true);
            });
        }
   });

   return query;
}

example:

Map<String, dynamic> params = {'aa': 1.1, 'bb': [2, [3, ['5', {'66': 777}]]]};
String query = getQueryString(params);
print(query);

this code will print:

&aa=1.1&bb[0]=2&bb[1][0]=3&bb[1][1][0]=5&bb[1][1][1][66]=777