In my flutter project I have some libraries that are using Uint8List (mostly cryptography stuff), and some libraries that are using List<int>(grpc).
I want to unify a bunch of functions that are working with bytes in best way possible.
Which cases are appropriate for Uint8List and List (which way is better to work with bytes in dart lang)?
Uint8List is a specialized type of List<int>. As explained by the Uint8List documentation:
For long lists, this implementation can be considerably more space- and time-efficient than the default
Listimplementation.Integers stored in the list are truncated to their low eight bits, interpreted as an unsigned 8-bit integer with values in the range 0 to 255.
You should prefer using Uint8List for bytes. There are a number of functions that take or return sequences of bytes as List<int>, but usually that's for historical reasons, and changing those APIs to use Uint8List now would break existing code. (There was an attempt to change the APIs, but it broke more code than expected and changes to some of the APIs had to be reverted.)
In cases where functions return a sequence of bytes as List<int>, usually the returned object is actually a Uint8List, so casting it often will work:
var list = foo() as Uint8List;
If you're unsure, you could write a helper function that performs the cast if possible but falls back to copying the List<int> into a new Uint8List object:
import 'dart:typed_data';
/// Converts a `List<int>` to a [Uint8List].
///
/// Attempts to cast to a [Uint8List] first to avoid creating an unnecessary
/// copy.
extension AsUint8List on List<int> {
Uint8List asUint8List() {
final self = this; // Local variable to allow automatic type promotion.
return (self is Uint8List) ? self : Uint8List.fromList(this);
}
}
and use it as:
var list = foo().asUint8List();
(The asUint8List() extension also is available via my dartbag package.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With