Reputation: 17587
I need to encode some binary blob (say, 100KB) in Dart code. Do not want to put it in a separate file, but hope can put it in .dart
code (because, for example, I want the excellent flutter hot restart instead of rebuilding the Flutter app again and again if the file chages).
What is the most brief way to do so?
For example I can come up with final bytes = [100, 70, 220, 132, ...];
but it will make the .dart
file huge.
I can also do final data = 'aGVsbG8...'
and use it by base64.decode(data)
, but it takes up 33% extra space in generated binary.
Upvotes: 0
Views: 457
Reputation: 4731
I recently confronted this problem and found a solution better than the base64 encoding. You can utilize unicode characters from '\x00'
to 'xff'
like the following example.
import 'dart:typed_data';
void main() {
final bytes = Uint8List.fromList("\x01\x02\xfe\xff".codeUnits);
for (var b in bytes) {
print(b);
}
}
This produces an efficient executable with 4 bytes "\x01\x02\xfe\xff" data, at least in my Linux Box.
Upvotes: 0
Reputation: 3219
Unfortunately those are your options as there's no way to export binary data from a file (i.e., like directly generating a .o
file that exports a symbol in C/C++) without using either a Dart list or some other form of encoding.
However, if you're dealing with fixed binary data representations, I'd highly recommend looking at types provided in dart:typed_data
to ensure you're storing this data in memory efficiently (e.g., using UInt8List
vs List<int>
will use 8-bits per element instead of the 64-bits that can be represented by int
).
Upvotes: 0