Mastering the mapToQuery Method in Dart: A Comprehensive Guide

Introduction

Mohammad Mahdi
3 min readJul 23, 2024

When working with APIs in Dart, constructing query strings is a common task. This involves converting a map of key-value pairs into a properly formatted query string. In this blog post, we will dive deep into the mapToQuery method, which efficiently handles this conversion. This method is particularly useful when you need to build dynamic query strings for your HTTP requests.

What is a Query String?

A query string is a part of a URL that assigns values to specified parameters. It typically follows the question mark (?) in a URL and consists of key-value pairs separated by ampersands (&). For example:

https://example.com/api?param1=value1&param2=value2

The mapToQuery Method

The mapToQuery method is designed to convert a Map<String, String?> into a query string. Let's break down the implementation step by step.

Implementation

import 'dart:convert';

String mapToQuery(Map<String, String?> map, {Encoding? encoding}) {
encoding ??= utf8;

// Remove keys with null values
map.removeWhere((key, value) => value == null);

// Create a list of key-value pairs
var pairs = <String>[];
map.forEach((key, value) {
pairs.add(
'${Uri.encodeQueryComponent(key, encoding: encoding!)}=${Uri.encodeQueryComponent(value!, encoding: encoding)}');
});

// Join the pairs with '&' to form the query string
return pairs.join("&");
}

Step-by-Step Explanation

  1. Import the Necessary Library:
import 'dart:convert';
  • This imports the dart:convert library, which provides the Encoding class.

2. Define the Method Signature:

String mapToQuery(Map<String, String?> map, {Encoding? encoding})
  • The method takes a Map<String, String?> and an optional Encoding parameter. If no encoding is provided, it defaults to utf8.

3. Set Default Encoding:

encoding ??= utf8;
  • If encoding is null, it is set to utf8.

4. Remove Null Values:

map.removeWhere((key, value) => value == null);
  • This removes any key-value pairs from the map where the value is null. This is important to avoid null-related errors.

5. Create Key-Value Pairs:

var pairs = <String>[];
map.forEach((key, value) {
pairs.add(
'${Uri.encodeQueryComponent(key, encoding: encoding!)}=${Uri.encodeQueryComponent(value!, encoding: encoding)}');
});
  • This loop goes through each key-value pair in the map, encodes both the key and the value using Uri.encodeQueryComponent, and adds them to the pairs list.

6. Join Pairs into Query String:

return pairs.join("&");

Finally, the method joins all pairs using the & character to form the complete query string.

Usage Example

Here’s an example of how you might use the mapToQuery method in a Dart application:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> fetchData() async {
final baseUrl = 'https://example.com/api';
final queryParameters = {
'param1': 'value1',
'param2': 'value2',
'param3': null,
};

final queryString = mapToQuery(queryParameters);
final url = '$baseUrl?$queryString';

final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
print('Response data: ${response.body}');
} else {
print('Failed to fetch data');
}
}

In this example, the mapToQuery method converts the queryParameters map into a query string, which is then appended to the base URL to form the complete request URL.

Conclusion

The mapToQuery method is a handy utility for converting a map of key-value pairs into a query string, making it easier to construct URLs for API requests. By handling null values and providing a flexible encoding option, this method ensures that your query strings are both valid and efficient.

Mastering this utility will streamline your API interactions and enhance your Dart and Flutter development experience. Happy coding!

--

--

Responses (1)