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 classeshashCode
Methods andequals
Method to implement.
hashCode
The method is used to return the hash code of the object, which is an integer. In custom classes, overridehashCode
Method to ensure that equal objects have the same hash code.equals
Methods are used to compare whether two objects are equal. In custom classes, overrideequals
Method to ensure that equal objects returntrue
。
Here is a sample custom classPerson
, it implementshashCode
andequals
method:
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 usename
andage
attribute to calculate the hash code andequals
Compare these two properties in the method.
That way, if twoPerson
Objects have the samename
andage
properties, they will be treated as equal objects.
Now, you can create a Set to storePerson
Object, 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 objectname
andage
property.
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!