跳到主要内容

记录

记录是一种匿名、不可变、聚合类型。像其他 集合类型 一样,它们允许你将多个对象打包成一个对象。与其他集合类型不同,记录是固定大小、异构且类型化的。

记录是实际的值;你可以将它们存储在变量中,嵌套它们,在函数之间传递它们,以及将它们存储在列表、映射和集合等数据结构中。

记录语法

#

记录表达式 是用逗号分隔的命名或位置字段列表,用括号括起来

dart
var record = ('first', a: 2, b: true, 'last');

记录类型注解 是用逗号分隔并用括号括起来的类型列表。你可以使用记录类型注解来定义返回类型和参数类型。例如,以下 (int, int) 语句是记录类型注解

dart
(int, int) swap((int, int) record) {
  var (a, b) = record;
  return (b, a);
}

记录表达式和类型注解中的字段反映了 函数中参数和实参 的工作方式。位置字段直接放在括号内

dart
// Record type annotation in a variable declaration:
(String, int) record;

// Initialize it with a record expression:
record = ('A string', 123);

在记录类型注解中,命名字段位于用花括号分隔的类型-名称对部分中,紧随所有位置字段之后。在记录表达式中,名称位于每个字段值之前,后面跟一个冒号

dart
// Record type annotation in a variable declaration:
({int a, bool b}) record;

// Initialize it with a record expression:
record = (a: 123, b: true);

记录类型中命名字段的名称是 记录类型定义 或其 形状 的一部分。两个具有不同命名字段名称的记录具有不同的类型

dart
({int a, int b}) recordAB = (a: 1, b: 2);
({int x, int y}) recordXY = (x: 3, y: 4);

// Compile error! These records don't have the same type.
// recordAB = recordXY;

在记录类型注解中,你也可以命名 位置 字段,但这些名称纯粹用于文档,不影响记录的类型

dart
(int a, int b) recordAB = (1, 2);
(int x, int y) recordXY = (3, 4);

recordAB = recordXY; // OK.

这类似于 函数声明或函数类型定义 中的位置参数可以有名称,但这些名称不影响函数的签名。

有关更多信息和示例,请查看 记录类型记录相等性

记录字段

#

记录字段可通过内置的 getter 访问。记录是不可变的,因此字段没有 setter。

命名字段公开同名 getter。位置字段公开名称为 $<position> 的 getter,跳过命名字段

dart
var record = ('first', a: 2, b: true, 'last');

print(record.$1); // Prints 'first'
print(record.a); // Prints 2
print(record.b); // Prints true
print(record.$2); // Prints 'last'

为了进一步简化记录字段访问,请查看 模式 页面。

记录类型

#

没有针对单个记录类型的类型声明。记录是根据其字段的类型进行结构化类型化的。记录的 形状(其字段集、字段类型以及它们的名称(如果有))唯一地决定了记录的类型。

记录中的每个字段都有自己的类型。同一记录中的字段类型可以不同。类型系统在从记录访问每个字段时都了解其类型

dart
(num, Object) pair = (42, 'a');

var first = pair.$1; // Static type `num`, runtime type `int`.
var second = pair.$2; // Static type `Object`, runtime type `String`.

考虑两个不相关的库,它们创建的记录具有相同的字段集。类型系统理解这些记录是相同的类型,即使这些库彼此不耦合。

记录相等性

#

如果两个记录具有相同的 形状(字段集)并且其相应字段具有相同的值,则它们相等。由于命名字段的 顺序 不是记录形状的一部分,因此命名字段的顺序不影响相等性。

例如

dart
(int x, int y, int z) point = (1, 2, 3);
(int r, int g, int b) color = (1, 2, 3);

print(point == color); // Prints 'true'.
dart
({int x, int y, int z}) point = (x: 1, y: 2, z: 3);
({int r, int g, int b}) color = (r: 1, g: 2, b: 3);

print(point == color); // Prints 'false'. Lint: Equals on unrelated types.

记录根据其字段的结构自动定义 hashCode== 方法。

多重返回

#

记录允许函数返回捆绑在一起的多个值。要从返回中检索记录值,请使用 模式匹配 将值 解构 到局部变量中。

dart
// Returns multiple values in a record:
(String name, int age) userInfo(Map<String, dynamic> json) {
  return (json['name'] as String, json['age'] as int);
}

final json = <String, dynamic>{'name': 'Dash', 'age': 10, 'color': 'blue'};

// Destructures using a record pattern with positional fields:
var (name, age) = userInfo(json);

/* Equivalent to:
  var info = userInfo(json);
  var name = info.$1;
  var age  = info.$2;
*/

你还可以使用记录的 命名字段,通过冒号 : 语法来解构记录,你可以在 模式类型 页面了解更多信息

dart
({String name, int age}) userInfo(Map<String, dynamic> json)
// ···
// Destructures using a record pattern with named fields:
final (:name, :age) = userInfo(json);

你可以在不使用记录的情况下从函数返回多个值,但其他方法存在缺点。例如,创建类会更加冗长,而使用 ListMap 等其他集合类型会失去类型安全。

记录作为简单数据结构

#

记录只保存数据。当你只需要数据时,它们立即可用且易于使用,无需声明任何新类。对于一个所有元组都具有相同形状的简单数据列表,*记录列表* 是最直接的表示。

例如,以下是“按钮定义”列表

dart
final buttons = [
  (
    label: "Button I",
    icon: const Icon(Icons.upload_file),
    onPressed: () => print("Action -> Button I"),
  ),
  (
    label: "Button II",
    icon: const Icon(Icons.info),
    onPressed: () => print("Action -> Button II"),
  )
];

这段代码可以直接编写,无需任何额外的声明。

记录与类型定义

#

你可以选择使用 类型定义 来为记录类型本身命名,并使用该名称而不是完整地写出记录类型。这种方法允许你声明某些字段可以为 null (?),即使列表中当前没有任何条目具有 null 值。

dart
typedef ButtonItem = ({String label, Icon icon, void Function()? onPressed});
final List<ButtonItem> buttons = [
  // ...
];

由于记录类型是结构类型,因此像 ButtonItem 这样的命名只是引入了一个别名,使其更容易引用结构类型:({String label, Icon icon, void Function()? onPressed})

让所有代码都通过别名引用记录类型,可以更轻松地在以后更改记录的实现,而无需更新每个引用。

代码可以像处理简单类实例一样处理给定的按钮定义

dart
List<Container> widget = [
  for (var button in buttons)
    Container(
      margin: const EdgeInsets.all(4.0),
      child: OutlinedButton.icon(
        onPressed: button.onPressed,
        icon: button.icon,
        label: Text(button.label),
      ),
    ),
];

你甚至可以在以后决定将记录类型更改为类类型以添加方法

dart
class ButtonItem {
  final String label;
  final Icon icon;
  final void Function()? onPressed;
  ButtonItem({required this.label, required this.icon, this.onPressed});
  bool get hasOnpressed => onPressed != null;
}

或更改为 扩展类型

dart
extension type ButtonItem._(({String label, Icon icon, void Function()? onPressed}) _) {
  String get label => _.label;
  Icon get icon => _.icon;
  void Function()? get onPressed => _.onPressed;
  ButtonItem({required String label, required Icon icon, void Function()? onPressed})
      : this._((label: label, icon: icon, onPressed: onPressed));
  bool get hasOnpressed => _.onPressed != null;
}

然后使用该类型的构造函数创建按钮定义列表

dart
final List<ButtonItem> buttons =  [
  ButtonItem(
    label: "Button I",
    icon: const Icon(Icons.upload_file),
    onPressed: () => print("Action -> Button I"),
  ),
  ButtonItem(
    label: "Button II",
    icon: const Icon(Icons.info),
    onPressed: () => print("Action -> Button II"),
  )
];

同样,所有这些操作都不需要更改使用该列表的代码。

更改任何类型都要求使用它的代码非常小心,不要做出假设。类型别名不能为将其用作引用的代码提供任何保护或保证,即别名值是记录。扩展类型也提供很少的保护。只有类才能提供完整的抽象和封装。