Dart Uri.dataFromBytes()
Syntax & Examples
Uri.dataFromBytes constructor
The `Uri.dataFromBytes` constructor in Dart creates a `data:` URI containing an encoding of bytes.
Syntax of Uri.dataFromBytes
The syntax of Uri.Uri.dataFromBytes constructor is:
Uri.dataFromBytes(List<int> bytes, { dynamic mimeType: "application/octet-stream" Map<String, String> parameters, dynamic percentEncoded: false })
This Uri.dataFromBytes constructor of Uri creates a data:
URI containing an encoding of bytes
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
bytes | required | The list of integers representing the bytes to include in the data URI. |
mimeType | optional | The MIME type of the data. Defaults to 'application/octet-stream'. |
parameters | optional | Additional parameters for the data URI as key-value pairs. |
percentEncoded | optional | A boolean flag indicating whether the bytes should be percent-encoded. Defaults to false. |
✐ Examples
1 Creating a basic data URI from bytes
In this example,
- We create a list of integers representing ASCII values for 'Hello'.
- We use the `Uri.dataFromBytes` constructor to create a data URI from these bytes.
- We print the URI as a string.
Dart Program
void main() {
List<int> bytes = [72, 101, 108, 108, 111];
Uri uri = Uri.dataFromBytes(bytes);
print(uri.toString());
}
Output
data:application/octet-stream;base64,SGVsbG8=
2 Creating a data URI with a custom MIME type
In this example,
- We create a list of integers representing ASCII values for 'Hello'.
- We use the `Uri.dataFromBytes` constructor with a custom MIME type 'text/plain'.
- We print the URI as a string.
Dart Program
void main() {
List<int> bytes = [72, 101, 108, 108, 111];
Uri uri = Uri.dataFromBytes(bytes, mimeType: 'text/plain');
print(uri.toString());
}
Output
data:text/plain;base64,SGVsbG8=
3 Creating a data URI with additional parameters
In this example,
- We create a list of integers representing ASCII values for 'Hello'.
- We use the `Uri.dataFromBytes` constructor with additional parameters, setting the charset to 'UTF-8'.
- We print the URI as a string.
Dart Program
void main() {
List<int> bytes = [72, 101, 108, 108, 111];
Uri uri = Uri.dataFromBytes(bytes, parameters: {'charset': 'UTF-8'});
print(uri.toString());
}
Output
data:application/octet-stream;charset=UTF-8;base64,SGVsbG8=
Summary
In this Dart tutorial, we learned about Uri.dataFromBytes constructor of Uri: the syntax and few working examples with output and detailed explanation for each example.