The Dart convert library is a powerful tool for encoding and decoding data in various formats. It provides efficient methods for working with JSON, UTF-8, and Base64 conversions, making it an essential part of many Dart applications.
JSON (JavaScript Object Notation) is a popular data format used for data exchange. The convert library offers simple methods to convert between Dart objects and JSON strings.
import 'dart:convert';
void main() {
Map person = {
'name': 'John Doe',
'age': 30,
'city': 'New York'
};
String jsonString = jsonEncode(person);
print(jsonString);
}
This example demonstrates how to convert a Dart Map to a JSON string using the jsonEncode()
function.
import 'dart:convert';
void main() {
String jsonString = '{"name":"Jane Smith","age":25,"city":"London"}';
Map person = jsonDecode(jsonString);
print(person['name']); // Output: Jane Smith
}
This code snippet shows how to parse a JSON string into a Dart object using the jsonDecode()
function.
UTF-8 is a widely used character encoding capable of representing any Unicode character. The convert library provides methods for encoding and decoding UTF-8 strings.
import 'dart:convert';
void main() {
String originalString = 'Hello, 世界!';
List encodedBytes = utf8.encode(originalString);
String decodedString = utf8.decode(encodedBytes);
print('Encoded bytes: $encodedBytes');
print('Decoded string: $decodedString');
}
This example illustrates UTF-8 encoding and decoding using the utf8.encode()
and utf8.decode()
methods.
Base64 encoding is commonly used to encode binary data for transmission over text-based protocols. The convert library simplifies Base64 operations in Dart.
import 'dart:convert';
void main() {
String originalString = 'Dart is awesome!';
String base64String = base64Encode(utf8.encode(originalString));
String decodedString = utf8.decode(base64Decode(base64String));
print('Base64 encoded: $base64String');
print('Decoded string: $decodedString');
}
This code demonstrates Base64 encoding and decoding using the base64Encode()
and base64Decode()
functions.
try-catch
blocks to gracefully handle encoding and decoding errors.The Dart convert library is a versatile tool for handling various data conversions. By mastering its functions, developers can efficiently work with JSON, UTF-8, and Base64 encodings in their Dart applications. For more advanced usage, explore the Dart async library to handle conversions asynchronously.