Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a List of Bytes?

Tags:

flutter

dart

I'm working in a project wherein I want to use a byte type for a variable. But when I try byte varName or List<byte> varName, the keyword byte is underlined. I want to do a thing like that

List<byte> varName = [0, 2, 5 ,7, ..., ..., x];

But it doesn't work.

like image 408
FQDEV Avatar asked Oct 19 '25 03:10

FQDEV


2 Answers

What you want is a Uint8List, not a List<byte> or List<int>.

Think about it: There's 8 bits in one byte. Therefore, a Java List is storing 8 bits in each item. In the same way, a Uint8List stores 8 bits per item, or one byte per item.

The way that you would do this using the provided code:

import 'dart:typed_data'; //Bundled with Dart

Uint8List example = Uint8List.fromList([0, 2, 5 ,7, ..., ..., x]); //Uint8List of bytes

You could also technically use List<int>, but then bitwise operations become more tricky, so I wouldn't recommend it.

like image 131
AKushWarrior Avatar answered Oct 22 '25 04:10

AKushWarrior


A byte is just a number between 0 and 255, so it's fine to declare a list of bytes like so:

List<int> byteList = [0, 2, 5, 7, 42, 255];

However, the int type holds 64-bit values, so it's a little overkill for 8-bit values. For small lists it doesn't matter, but for large lists the Uint8List type better for the job:

// import 'dart:typed_data';

Uint8List byteList = Uint8List.fromList([0, 2, 5, 7, 42, 255]);

Uint8List is fixed size and holds unsigned 8-bit values.

like image 32
Suragch Avatar answered Oct 22 '25 03:10

Suragch