Flutter Set存储自定义对象时 如何保证唯一

在Flutter中,Set和List是两种不同的集合类型,List中存储的元素可以重复,Set中存储的元素不可重复。

如果想在Set中存储自定义对象,需要确保对象的唯一性。

可以通过在自定义类中实现hashCode方法和equals方法来实现。

  • hashCode方法用于返回对象的哈希码,这是一个整数。在自定义类中,需要覆盖hashCode方法以确保相等的对象具有相同的哈希码。

  • equals方法用于比较两个对象是否相等。在自定义类中,需要覆盖equals方法以确保相等的对象返回true

下面是一个示例自定义类Person,它实现了hashCodeequals方法:

dart 复制代码
class Person {
  final String name;
  final int age;

  Person(this.name, this.age);

  @override
  int get hashCode => name.hashCode ^ age.hashCode;

  @override
  bool get equals(other) => other is Person && other.name == name && other.age == age;
}

在这个例子中,我们使用nameage属性来计算哈希码,并在equals方法中比较这两个属性。

这样,如果两个Person对象具有相同的nameage属性,它们将被视为相等的对象。

现在,可以创建一个Set来存储Person对象,并且Set将确保每个对象是唯一的:

dart 复制代码
Set<Person> people = new Set();

people.add(Person('Alice', 25));
people.add(Person('Bob', 30));
people.add(Person('Alice', 25)); 
// 这个重复的对象不会被添加到Set中

people.forEach((person) => print(person)); 
// 输出Set中的每个Person对象

在这个例子中,第三个对象是重复的,因为它与第一个对象具有相同的nameage属性。

Set会自动忽略重复的对象,确保每个对象是唯一的。

相关推荐
lqj_本人1 天前
flutter_鸿蒙next_Dart基础②List
flutter
lqj_本人1 天前
flutter_鸿蒙next_Dart基础①字符串
flutter
The_tuber_sadness1 天前
【Flutter】- 基础语法
flutter
helloxmg1 天前
鸿蒙harmonyos next flutter通信之BasicMessageChannel获取app版本号
flutter
linpengteng2 天前
使用 Flutter 开发数字钱包应用(Dompet App)
前端·flutter·firebase
云兮Coder2 天前
鸿蒙 HarmonyNext 与 Flutter 的异同之处
flutter·华为·harmonyos
lqj_本人2 天前
flutter_鸿蒙next(win)环境搭建
flutter·华为·harmonyos
yuanlaile3 天前
Windows上面搭建Flutter Android运行环境
android·flutter