5.4 C
New York
Tuesday, December 5, 2023

Dart: Convert Map to Query String and vice versa

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.Advertisements

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?.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 it like this:

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

  Uri _myUri = 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

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

Example

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

  print(_result);
}

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

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

One More Example

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

void main() {
  const 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);
}
Advertisements

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.

Advertisements

Related Articles

Latest Articles