SoFunction
Updated on 2025-04-10

Detailed explanation of the only way to ensure that Flutter Set is storing custom objects

In Flutter, Set and List are two different collection types. The elements stored in List can be repeated, while the elements stored in Set cannot be repeated.

If you want to store custom objects in Set, you need to ensure the uniqueness of the objects.

Can be implemented in custom classeshashCodeMethods andequalsMethod to implement.

  • hashCodeThe method is used to return the hash code of the object, which is an integer. In custom classes, overridehashCodeMethod to ensure that equal objects have the same hash code.

  • equalsMethods are used to compare whether two objects are equal. In custom classes, overrideequalsMethod to ensure that equal objects returntrue

Here is a sample custom classPerson, it implementshashCodeandequalsmethod:

class Person {
  final String name;
  final int age;

  Person(, );

  @override
  int get hashCode =>  ^ ;

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

In this example, we usenameandageattribute to calculate the hash code andequalsCompare these two properties in the method.

That way, if twoPersonObjects have the samenameandageproperties, they will be treated as equal objects.

Now, you can create a Set to storePersonObject, and Set will ensure that each object is unique:

Set<Person> people = new Set();

(Person('Alice', 25));
(Person('Bob', 30));
(Person('Alice', 25)); 
// This duplicate object will not be added to the Set
((person) => print(person)); 
// Output each Person object in the Set

In this example, the third object is repeated because it has the same as the first objectnameandageproperty.

Set will automatically ignore duplicate objects, ensuring that each object is unique.

This is the article about the only way to ensure that Flutter Set stores custom objects. For more information about Flutter Set stores custom objects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!