Dart| Flutter How to: Convert Map to Query String with example

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.

  • Convert Query String to Map, pass Map to queryParameters in the Uri constructor
  • Convert Map to Query String using the Uri.splitQueryString() method

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 the Dart

  var employee = {"email": "[email protected]", "id": "1"};

you want to output

http://dev.localhost.com:8080/?email=abc%40abc.com&id=1

URL class contains a constructor with the 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": "[email protected]", "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 parses the query string and converts it into Map.

There are multiple ways we can do it.

  • using Uri splitQueryString method: The Uri class has the splitQueryString 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 call queryParameters 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: [email protected], id: 1}

  final Map<String, dynamic> map1 = Uri.splitQueryString(completeUrl);
  print(map1); // {http://dev.localhost.com:8080/?email: [email protected], id: 1}

  final Uri url1 = Uri.parse(queryString);
  print(url1.queryParameters); // {}

  final Uri url2 = Uri.parse(completeUrl);
  print(url2.queryParameters); //{email: [email protected], id: 1}
}

output

{email: abc@abc.com, id: 1}
{http://dev.localhost.com:8080/?email: [email protected], id: 1}
{}
{email: abc@abc.com, id: 1}

Conclusion

Learned how to parse query string into map and vice versa in dart and flutter