Dart: Convert Map to Query String and vice versa

Last updated on June 9, 2021 A Goodman Loading... Post a comment

This article shows you how to turn a given map into a query string and parse a given query string into a map in Dart (and Flutter as well) without using any third-party packages.

Convert a Map to a Query String

We can use the queryParameters parameter of the Uri class to make a query string from a map. Note that the Uri class goes with dart:core so that you can use it without importing anything.

Example

void main() {
  final Map<String, dynamic> _myMap = {
    'name': 'John Doe',
    'age': 35,
    'job': 'Flutter dev'
  };

  final String _queryString = Uri(
      queryParameters: _myMap.map((key, value) =>
          MapEntry(key, value == null ? null : value.toString()))).query;

  print(_queryString);
}

Output:

name=John+Doe&age=35&job=Flutter+dev

Another Example

If you want to construct a full url, you can do like this:

void main() {
  final Map<String, dynamic> _myMap = {
    'category': 'mobile',
    'subCategory': 'ios'
  };

  Uri _myUri = new Uri(
      scheme: 'https',
      host: 'www.kindacode.com',
      path: 'example/search/query',
      queryParameters: _myMap);

  print(_myUri);
}

Output:

https://www.kindacode.com/example/search/query?category=mobile&subCategory=ios

Parse a Query String to a Map

The splitQueryString static method from the Uri class can help you easily parse a query string into a map.

Example

void main() {
  final String _query = 'name=John+Doe&age=35&job=Flutter+dev';
  final Map<String, dynamic> _result = Uri.splitQueryString(_query);

  print(_result);
}

An here is the output you will see in your terminal:

{name: John Doe, age: 35, job: Flutter dev}

One More Example

If your are given a full URL instead of a query string, you can do like this:

void main() {
  final String _url =
      'https://www.kindacode.com/example/search/query?category=mobile&subCategory=ios';

  final Uri _myUri = Uri.parse(_url);

  final Map<String, dynamic> _result = _myUri.queryParameters;
  print(_result);
}

Output:

{category: mobile, subCategory: ios}

Conclusion

You’ve learned how to convert maps into query strings and vice versa in Dart. These techniques can be helpful in some situations related to sending requests in applications. If you’d like to explore more exciting things about Dart and Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page, or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles