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

Uint8List vs List<int> what is the difference?

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

Uint8ListList<int> 的特殊类型。正如 the Uint8List documentation 所解释的:

For long lists, this implementation can be considerably more space- and time-efficient than the default List implementation.

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.

您应该更喜欢对字节使用 Uint8List。有许多函数采用或 return 字节序列作为 List<int>,但通常这是出于历史原因,现在将这些 API 更改为使用 Uint8List 会破坏现有代码。

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

var list = foo() as Uint8List;

如果您不确定,您可以编写一个辅助函数,在可能的情况下执行转换,但回退到将 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);
  }
}

并将其用作:

var list = foo().asUint8List();