This tutorial, Shows you multiple ways to convert a Map of values into URL Query String and Query String into the map. This works in Flutter also.
Query String is a key and value appended to URL separated by &
.
How to Convert Map to Query String in dart and flutter
Sometimes, We have a map of keys and values in Dart
var employee = {"email": "abc@abc.com", "id": "1"};
you want to output
http://dev.localhost.com:8080/?email=abc%40abc.com&id=1
URL class contains constrcutor with below parameters scheme,host,port,path,queryParameters
Uri Uri({
String? the scheme, String? userInfo, String? host, int? port, String? path, Iterable? pathSegments, String? query, Map<String, dynamic>? queryParameters, String? fragment, })
queryParameters
is a Map of String and dynamic.
Here is an example
void main() {
var employee = {"email": "abc@abc.com", "id": "1"};
Uri queryStringUrl = new Uri(
scheme: 'http',
host: 'dev.localhost.com',
port: 8080,
path: '/',
queryParameters: employee);
print(queryStringUrl);
}
Output:
http://dev.localhost.com:8080/?email=abc%40abc.com&id=1
How to Convert Query String to Map in dart and flutter?
This example parse query string, convert into Map.
There are multiple ways we can do it.
- using Uri splitQueryString method:
Uri
class has thesplitQueryString
method with query and encoding parameters.
Map<String, String> splitQueryString(String query, {Encoding encoding = utf8})
It takes the query string and returns the Map. It does not work with a Complete URL that contains the query string
- use Uri parse and
queryParameters
: First, Parse url using Uri.parse() method and callqueryParameters
property It takes the complete URL and converts it to Map. It does not work with a substring of URL ie query string.
Here is an example
void main() {
final String queryString = 'email=abc%40abc.com&id=1';
final String completeUrl =
'http://dev.localhost.com:8080/?email=abc%40abc.com&id=1';
final Map<String, dynamic> map = Uri.splitQueryString(queryString);
print(map); // {email: abc@abc.com, id: 1}
final Map<String, dynamic> map1 = Uri.splitQueryString(completeUrl);
print(map1); // {http://dev.localhost.com:8080/?email: abc@abc.com, id: 1}
final Uri url1 = Uri.parse(queryString);
print(url1.queryParameters); // {}
final Uri url2 = Uri.parse(completeUrl);
print(url2.queryParameters); //{email: abc@abc.com, id: 1}
}
output
{email: abc@abc.com, id: 1}
{http://dev.localhost.com:8080/?email: abc@abc.com, id: 1}
{}
{email: abc@abc.com, id: 1}
Conclusion
Learned how to parse query string into map and vice versa in dart and flutter