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?.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
The 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);
}
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:
- Dart: Find List Elements that Satisfy Conditions
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- Dart: Extract a substring from a given string (advanced)
- Flutter: 2 Ways to Make a Dark/Light Mode Toggle
- Conditional (Ternary) Operator in Dart and Flutter
- Flutter: Check Internet Connection without any plugins
You can also take a tour around our Flutter topic page or Dart topic page for the latest tutorials and examples.