I have a situation where I need to turn a Map
into a query String (after the first ?
). For instance if I have the following map:
Map json = {
"email": eml,
"password": passwd
};
And a base URL:
String baseURL = "http://localhost:8080/myapp";
Then I need something that converts the json Map
into the query string of the base URL:
String fullURL = parameterizeURL(baseURL, json);
// Prints: http://localhost:8080/myapp?email=blah&password=meh
// (if "blah" was entered as the email, and "meh" was entered as the password)
print(fullURL);
I found this query String-to-map library on Git, but I need the inverse of this! It would be great to get URL encoding in there as well.
I'm happy to make something homegrown but being so new to Dart I was wondering if there's anything on pub
/Github/the etherspehere that does this already.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With