Dart Uri.dataFromString()
Syntax & Examples
Uri.dataFromString constructor
The `Uri.dataFromString` constructor in Dart is used to create a `data:` URI containing the specified content string. This constructor allows specifying additional parameters such as MIME type, encoding, parameters, and whether the content should be base64 encoded.
Syntax of Uri.dataFromString
The syntax of Uri.Uri.dataFromString constructor is:
Uri.dataFromString(String content, { String mimeType, Encoding encoding, Map<String, String> parameters, bool base64: false })
This Uri.dataFromString constructor of Uri creates a data:
URI containing the content
string.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
content | required | The content string to include in the data URI. |
mimeType | optional | The MIME type of the content. Defaults to 'text/plain'. |
encoding | optional | The encoding used for the content. Defaults to UTF-8. |
parameters | optional | Additional parameters for the data URI as key-value pairs. |
base64 | optional | A boolean flag indicating whether the content should be base64-encoded. Defaults to false. |
✐ Examples
1 Creating a data URI with plain text content
In this example,
- We create a `String` variable `content` containing the text 'Hello, world!'.
- We use the `Uri.dataFromString` constructor to create a data URI with the specified content, MIME type 'text/plain', encoding UTF-8, and additional parameter 'charset=utf-8'.
- We print the data URI to standard output.
Dart Program
void main() {
String content = 'Hello, world!';
Uri dataUri = Uri.dataFromString(content, mimeType: 'text/plain', encoding: utf8, parameters: {'charset': 'utf-8'});
print(dataUri);
}
Output
data:text/html,%3Chtml%3E%3Cbody%3E%3Ch1%3EHello,%20world!%3C/h1%3E%3C/body%3E%3C/html%3E
2 Creating a data URI with HTML content
In this example,
- We create a `String` variable `htmlContent` containing a simple HTML document.
- We use the `Uri.dataFromString` constructor to create a data URI with the HTML content and MIME type 'text/html'.
- We print the data URI to standard output.
Dart Program
void main() {
String htmlContent = '<html><body><h1>Hello, world!</h1></body></html>';
Uri htmlDataUri = Uri.dataFromString(htmlContent, mimeType: 'text/html');
print(htmlDataUri);
}
Output
data:text/html,%3Chtml%3E%3Cbody%3E%3Ch1%3EHello,%20world!%3C/h1%3E%3C/body%3E%3C/html%3E
Summary
In this Dart tutorial, we learned about Uri.dataFromString constructor of Uri: the syntax and few working examples with output and detailed explanation for each example.