Uint8List 与 List<int> 有什么区别?

d1n*_*h8g 14 byte type-conversion dart

在我的 flutter 项目中,我有一些正在使用的库Uint8List(主要是密码学的东西),以及一些正在使用的库List<int>(grpc)。我想以尽可能最好的方式统一一堆使用字节的函数。哪些情况适合 Uint8List 和 List(哪种方式更适合在 dart lang 中处理字节)?

jam*_*lin 23

Uint8List是一种特殊类型List<int>。正如文档所解释Uint8List

对于长列表,此实现比默认实现更加节省空间和时间List

存储在列表中的整数被截断为低八位,解释为无符号 8 位整数,值范围为 0 到 255。

您应该更喜欢使用Uint8Listfor bytes。有许多函数接受或返回字节序列 as List<int>,但这通常是出于历史原因,并且现在更改这些 APIUint8List会破坏现有代码。(曾尝试更改 API,但破坏的代码比预期多,并且必须恢复对某些 API 的更改。)

在函数返回字节序列为 的情况下List<int>,通常返回的对象实际上是 a Uint8List,因此转换它通常会起作用:

var list = foo() as Uint8List;
Run Code Online (Sandbox Code Playgroud)

如果您不确定,您可以编写一个辅助函数,如果可能的话,它会执行强制转换,但会退回到将其复制List<int>到新Uint8List对象中:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

并将其用作:

var list = foo().asUint8List();
Run Code Online (Sandbox Code Playgroud)

(该asUint8List()扩展也可以通过我的dartbag包获得。)