Dart Equality, hashCode & Comparable Explained — Value Objects, Sorting & Practical Flutter Examples (2026 Guide)

Two Dart objects can contain exactly the same information and still be considered different.

That might sound surprising, especially when you’re building Flutter applications that compare products, manage favorites, remove duplicate records, or update immutable application state.

Consider this example:

class Product {
  final int id;
  final String name;

  Product(this.id, this.name);
}

void main() {
  final first = Product(1, 'Laptop');
  final second = Product(1, 'Laptop');

  print(first == second); // false
}

Both objects contain the same values. Why does Dart report false?

Because ordinary Dart class instances inherit identity-based equality unless their classes define another equality contract.

Understanding this distinction is essential for building reliable Flutter applications.

In this tutorial, we’ll explore object identity, equality operators, hash codes, immutable value objects, the Comparable interface, custom sorting, and collection behavior.

We’ll also build a complete Flutter Smart Product Comparator Lab, featuring product deduplication, sorting, favorites, and Material 3 UI.

This is Article 29 in the Moiks Developer Blog Flutter Tutorials series.


1. What You’ll Learn

By the end of this tutorial, you’ll understand:

  1. The difference between identity and value equality.
  2. How Dart’s == operator works.
  3. When to override operator ==.
  4. Why overriding hashCode is necessary.
  5. How Object.hash() and Object.hashAll() work.
  6. How HashSet and HashMap depend on equality.
  7. How to implement immutable value objects.
  8. How to implement Comparable<T>.
  9. How to use compareTo() and custom comparators.
  10. How to avoid inconsistent equality and sorting.
  11. How equality affects Flutter application state.
  12. How to test equality contracts and sorting behavior.

The examples use modern Dart 3 syntax and Flutter Material 3.

Part 1: Understanding Object Equality

2. Identity vs Equality in Dart

Dart provides two related but different concepts.

Identity answers whether two references refer to the same object.

Equality answers whether two objects should be considered equal according to their equality implementation.

Use identical() to test identity.

void main() {
  final first = <int>[1, 2, 3];
  final second = <int>[1, 2, 3];
  final third = first;

  print(identical(first, second)); // false
  print(identical(first, third));  // true
}

The first and second lists are different list instances.

The third variable refers to the first list.

For ordinary lists, == also uses identity-based equality.

print(first == second); // false

This is different from a value object whose equality has been defined using its contents.


3. How the Equality Operator Works

Every Dart object has an equality operator.

Its signature is:

bool operator ==(Object other);

By default, ordinary instances inherit Object equality behavior.

You can override the operator to define value-based comparison.

For example:

final class Point {
  final int x;
  final int y;

  const Point(this.x, this.y);

  @override
  bool operator ==(Object other) {
    return identical(this, other) ||
        other is Point &&
            x == other.x &&
            y == other.y;
  }

  @override
  int get hashCode => Object.hash(x, y);
}

Usage:

void main() {
  const first = Point(10, 20);
  const second = Point(10, 20);
  const third = Point(20, 10);

  print(first == second); // true
  print(first == third);  // false
}

Here, equality depends on the coordinates rather than object identity.

Why Check identical()?

The expression:

identical(this, other)

provides a fast path when both references point to the same object.

It is a common optimization, but it is not required for a correct value equality implementation.


4. The Properties of a Good Equality Contract

For normal value objects, equality should follow several important rules.

Reflexive

An object should equal itself.

a == a

Symmetric

If a == b, then b == a.

Transitive

If a == b and b == c, then a == c.

Consistent

Equality should not unexpectedly change while objects are used in collections.

These properties are important for predictable behavior in sets, maps, caches, and state-management code.

In particular, equality fields should generally be immutable.


Part 2: Understanding hashCode

5. What Is hashCode in Dart?

Every Dart object exposes a hashCode property.

Hash-based collections use hash codes to organize and locate elements efficiently.

Examples include:

  • HashSet
  • HashMap
  • The default equality-based behavior of ordinary Dart sets and maps

A hash code is not a unique identifier.

Different objects can produce the same hash code.

Such collisions are expected and must be handled by hash-based collections.


6. The Most Important hashCode Rule

If two objects are equal, their hash codes must also be equal.

In other words:

if (a == b) {
  assert(a.hashCode == b.hashCode);
}

The reverse is not required.

Two objects may have the same hash code without being equal.

Incorrect Implementation

class BadProduct {
  final int id;

  BadProduct(this.id);

  @override
  bool operator ==(Object other) =>
      other is BadProduct && id == other.id;
}

This class overrides equality without providing a matching hash code.

That can cause incorrect behavior in hash-based collections.

Correct Implementation

final class ProductId {
  final int value;

  const ProductId(this.value);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is ProductId && value == other.value;

  @override
  int get hashCode => value.hashCode;
}

Now two ProductId objects containing the same integer are equal and have matching hash codes.


7. Object.hash() Explained

When equality depends on multiple fields, Dart provides Object.hash().

final class Address {
  final String city;
  final String country;

  const Address({
    required this.city,
    required this.country,
  });

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Address &&
          city == other.city &&
          country == other.country;

  @override
  int get hashCode => Object.hash(city, country);
}

Object.hash() combines the supplied values into a hash code.

Use the same fields in operator == and hashCode.

Do not rely on hash codes being stable across separate program executions or platforms. They are intended for in-memory hashing, not persistent identifiers.


8. Object.hashAll() Explained

For a variable-length collection of values, Dart provides Object.hashAll().

final numbers = [10, 20, 30];

final hash = Object.hashAll(numbers);

print(hash);

Object.hashAll() combines the hashes of the iterable’s elements.

However, it does not automatically make a class containing a list use deep equality.

For example, two separate lists containing the same values are still not equal using ordinary list ==.

If your model requires structural collection equality, implement it explicitly or use an appropriate collection equality utility.


Part 3: Equality in Collections

9. How Set Uses Equality

A set stores unique elements according to its equality behavior.

final values = <int>{1, 2, 2, 3};

print(values); // {1, 2, 3}

With custom objects, uniqueness depends on their equality and hash code implementations.

final ids = <ProductId>{
  const ProductId(100),
  const ProductId(100),
  const ProductId(200),
};

print(ids.length); // 2

Because ProductId defines value equality, the two objects containing 100 are considered duplicates.

This is especially useful for deduplicating API results.


10. How Map Uses Equality

Map keys also depend on equality.

final prices = <ProductId, double>{
  const ProductId(101): 999.0,
};

print(prices[const ProductId(101)]);

Output:

999.0

The lookup works because the new ProductId(101) is equal to the stored key and has a matching hash code.

Avoid Mutable Hash Keys

Never mutate the fields used to calculate equality or hash codes while an object is stored in a hash-based collection.

The collection may no longer be able to locate the object correctly.

Immutable value objects are a safer choice.


Part 4: Comparable and Sorting

11. What Is Comparable in Dart?

Dart provides the Comparable<T> interface for objects with a natural ordering.

For example, numbers and strings support comparison.

You can implement Comparable<T> in your own classes.

final class Score implements Comparable<Score> {
  final int value;

  const Score(this.value);

  @override
  int compareTo(Score other) {
    return value.compareTo(other.value);
  }
}

Usage:

void main() {
  final scores = [
    const Score(90),
    const Score(40),
    const Score(75),
  ];

  scores.sort();

  for (final score in scores) {
    print(score.value);
  }
}

Output:

40
75
90

The compareTo() method determines ordering.


12. Understanding compareTo() Results

A comparison method returns an integer.

ResultMeaning
NegativeFirst object comes before the second
ZeroBoth objects compare equally for sorting
PositiveFirst object comes after the second

Do not assume the result must be exactly -1, 0, or 1.

Only its sign matters.


13. Comparable vs Comparator

Comparable<T> defines a natural ordering for a type.

A Comparator<T> is a function that defines an ordering for a particular operation.

For example:

final prices = [499.0, 199.0, 999.0];

prices.sort((a, b) => b.compareTo(a));

print(prices);

Output:

[999.0, 499.0, 199.0]

The comparator reverses the normal numeric ordering.

For a product application, you might offer several sorting options:

  • Price: low to high.
  • Price: high to low.
  • Name: alphabetical.
  • Rating: highest first.

These are better represented by explicit comparators than by trying to make one natural ordering serve every purpose.


14. Equality and Sorting Must Be Designed Carefully

A subtle problem occurs when compareTo() and == disagree.

For example, two products might have the same price but different IDs.

A price-only comparator returns zero, even though the products are not equal.

This is valid for sorting a list, but it matters when using ordered sets or maps that treat comparison equality as uniqueness.

For a natural ordering intended to be consistent with equality, use a deterministic tie-breaker.

For example:

int compareProducts(Product a, Product b) {
  final priceResult = a.price.compareTo(b.price);

  if (priceResult != 0) {
    return priceResult;
  }

  return a.id.compareTo(b.id);
}

The product ID ensures that products with the same price but different IDs still have a defined order.


Part 5: Build Flutter Smart Product Comparator Lab

15. Application Overview

We’ll create an offline Flutter application with the following features:

  • Immutable product models.
  • Value equality based on product ID.
  • Consistent hash codes.
  • Duplicate product removal.
  • Product sorting.
  • Search by product name.
  • Favorite product selection.
  • A product statistics dashboard.
  • Material 3 interface.
  • Unit and widget tests.

This project uses Flutter’s built-in APIs without additional runtime dependencies.

Application Architecture

Smart Product Comparator Lab
│
├── Product Model
│   ├── Immutable fields
│   ├── operator ==
│   ├── hashCode
│   └── Comparable<Product>
│
├── Product Controller
│   ├── Deduplication
│   ├── Search
│   ├── Sorting
│   └── Favorites
│
├── Flutter UI
│   ├── Statistics
│   ├── Search
│   ├── Sort menu
│   └── Product cards
│
└── Automated Tests
    ├── Equality
    ├── Hashing
    ├── Sorting
    ├── Controller
    └── Widgets

16. Create the Flutter Project

Open your terminal and run:

flutter create smart_product_comparator_lab
cd smart_product_comparator_lab

Create the following files:

smart_product_comparator_lab/
├── lib/
│   ├── main.dart
│   ├── models/
│   │   └── product.dart
│   └── controllers/
│       └── product_controller.dart
└── test/
    ├── product_test.dart
    ├── product_controller_test.dart
    └── widget_test.dart

17. Create the Immutable Product Model

Code Block Pro — lib/models/product.dart

Language: Dart

final class Product implements Comparable<Product> {
  final int id;
  final String name;
  final double price;
  final double rating;

  const Product({
    required this.id,
    required this.name,
    required this.price,
    required this.rating,
  });

  Product copyWith({
    String? name,
    double? price,
    double? rating,
  }) {
    return Product(
      id: id,
      name: name ?? this.name,
      price: price ?? this.price,
      rating: rating ?? this.rating,
    );
  }

  @override
  bool operator ==(Object other) {
    return identical(this, other) ||
        other is Product && id == other.id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  int compareTo(Product other) {
    return id.compareTo(other.id);
  }

  @override
  String toString() {
    return 'Product(id: $id, name: $name, '
        'price: $price, rating: $rating)';
  }
}

Understanding the Equality Contract

This model deliberately uses ID-based equality.

Two products with the same ID represent the same logical product, even if their names or prices differ.

For example:

const first = Product(
  id: 1,
  name: 'Laptop',
  price: 50000,
  rating: 4.5,
);

const second = Product(
  id: 1,
  name: 'Updated Laptop',
  price: 49000,
  rating: 4.6,
);

print(first == second); // true

This behavior is appropriate when product IDs are unique, stable identifiers.

For a value object such as a coordinate or money amount, equality should generally include all fields that define the value.

Why compareTo() Uses ID

The natural ordering is based on the product ID.

This ensures that compareTo() returns zero exactly when products have the same ID.

Alternative sorting strategies such as price and rating will be implemented separately in the controller.


18. Create the Product Controller

Code Block Pro — lib/controllers/product_controller.dart

Language: Dart

import 'package:flutter/foundation.dart';

import '../models/product.dart';

enum ProductSort {
  nameAscending('Name: A to Z'),
  priceAscending('Price: Low to High'),
  priceDescending('Price: High to Low'),
  ratingDescending('Rating: Highest First');

  final String label;

  const ProductSort(this.label);
}

final class ProductController extends ChangeNotifier {
  ProductController({Iterable<Product>? initialProducts}) {
    _products = _deduplicate(
      initialProducts ?? sampleProducts,
    );
  }

  static const sampleProducts = <Product>[
    Product(
      id: 101,
      name: 'Wireless Headphones',
      price: 2499,
      rating: 4.6,
    ),
    Product(
      id: 102,
      name: 'Smart Watch',
      price: 3999,
      rating: 4.4,
    ),
    Product(
      id: 103,
      name: 'Bluetooth Speaker',
      price: 1799,
      rating: 4.7,
    ),
    Product(
      id: 104,
      name: 'USB-C Charger',
      price: 899,
      rating: 4.5,
    ),
    Product(
      id: 105,
      name: 'Laptop Stand',
      price: 1299,
      rating: 4.3,
    ),
    Product(
      id: 103,
      name: 'Duplicate Speaker',
      price: 1999,
      rating: 4.1,
    ),
  ];

  late List<Product> _products;

  final Set<int> _favoriteIds = <int>{};

  String _query = '';
  ProductSort _sort = ProductSort.nameAscending;

  String get query => _query;
  ProductSort get sort => _sort;

  int get totalProducts => _products.length;
  int get favoriteCount => _favoriteIds.length;

  List<Product> get visibleProducts {
    final normalized = _query.trim().toLowerCase();

    final results = _products
        .where(
          (product) =>
              product.name.toLowerCase().contains(normalized),
        )
        .toList();

    switch (_sort) {
      case ProductSort.nameAscending:
        results.sort((a, b) {
          final result = a.name.compareTo(b.name);
          return result != 0 ? result : a.id.compareTo(b.id);
        });

      case ProductSort.priceAscending:
        results.sort((a, b) {
          final result = a.price.compareTo(b.price);
          return result != 0 ? result : a.id.compareTo(b.id);
        });

      case ProductSort.priceDescending:
        results.sort((a, b) {
          final result = b.price.compareTo(a.price);
          return result != 0 ? result : a.id.compareTo(b.id);
        });

      case ProductSort.ratingDescending:
        results.sort((a, b) {
          final result = b.rating.compareTo(a.rating);
          return result != 0 ? result : a.id.compareTo(b.id);
        });
    }

    return results;
  }

  static List<Product> _deduplicate(
    Iterable<Product> products,
  ) {
    return products.toSet().toList();
  }

  void setQuery(String value) {
    _query = value;
    notifyListeners();
  }

  void setSort(ProductSort value) {
    _sort = value;
    notifyListeners();
  }

  bool isFavorite(Product product) {
    return _favoriteIds.contains(product.id);
  }

  void toggleFavorite(Product product) {
    if (!_favoriteIds.add(product.id)) {
      _favoriteIds.remove(product.id);
    }

    notifyListeners();
  }

  double get averagePrice {
    if (_products.isEmpty) return 0;

    final total = _products.fold<double>(
      0,
      (sum, product) => sum + product.price,
    );

    return total / _products.length;
  }
}

How Deduplication Works

The controller calls:

products.toSet().toList();

Because Product defines equality and hash codes using its ID, duplicate IDs are removed.

In this demo, the first encountered product for an ID is retained.

This is a deliberate business rule. Real applications may instead prefer the latest server record, a version number, or an explicit merge strategy.

Why Use a Set for Favorites?

Favorites are stored as product IDs:

final Set<int> _favoriteIds = <int>{};

A set is appropriate because an item can either be a favorite or not.

There is no reason to store the same favorite ID multiple times.

Why Sort a Copy?

The controller creates a new list before sorting.

This prevents the UI’s selected sort order from mutating the underlying product collection.


19. Build the Complete Material 3 UI

Code Block Pro — lib/main.dart

Language: Dart

import 'package:flutter/material.dart';

import 'controllers/product_controller.dart';
import 'models/product.dart';

void main() {
  runApp(const SmartProductComparatorApp());
}

class SmartProductComparatorApp extends StatelessWidget {
  const SmartProductComparatorApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Smart Product Comparator Lab',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF004B64),
        ),
      ),
      home: const ProductComparatorScreen(),
    );
  }
}

class ProductComparatorScreen extends StatefulWidget {
  const ProductComparatorScreen({super.key});

  @override
  State<ProductComparatorScreen> createState() =>
      _ProductComparatorScreenState();
}

class _ProductComparatorScreenState
    extends State<ProductComparatorScreen> {
  late final ProductController controller;

  @override
  void initState() {
    super.initState();
    controller = ProductController();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  String formatPrice(double price) {
    return '₹${price.toStringAsFixed(0)}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Smart Product Comparator'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 850),
            child: AnimatedBuilder(
              animation: controller,
              builder: (context, child) {
                final products = controller.visibleProducts;

                return ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    _buildHeader(),
                    const SizedBox(height: 16),
                    _buildStatistics(),
                    const SizedBox(height: 16),
                    _buildSearchAndSort(),
                    const SizedBox(height: 20),
                    Text(
                      'Products (${products.length})',
                      style: Theme.of(context)
                          .textTheme
                          .titleLarge,
                    ),
                    const SizedBox(height: 12),
                    if (products.isEmpty)
                      const Card(
                        child: Padding(
                          padding: EdgeInsets.all(24),
                          child: Text(
                            'No matching products found.',
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    for (final product in products)
                      _buildProductCard(product),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            const Icon(
              Icons.compare_arrows,
              size: 48,
              color: Color(0xFF004B64),
            ),
            const SizedBox(height: 12),
            Text(
              'Dart Equality & Sorting Lab',
              style: Theme.of(context)
                  .textTheme
                  .headlineSmall,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            const Text(
              'Value Equality • hashCode • Comparable',
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatistics() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Wrap(
          spacing: 28,
          runSpacing: 16,
          alignment: WrapAlignment.spaceEvenly,
          children: [
            _metric(
              'Unique Products',
              '${controller.totalProducts}',
              Icons.inventory_2_outlined,
            ),
            _metric(
              'Favorites',
              '${controller.favoriteCount}',
              Icons.favorite_outline,
            ),
            _metric(
              'Average Price',
              formatPrice(controller.averagePrice),
              Icons.payments_outlined,
            ),
          ],
        ),
      ),
    );
  }

  Widget _metric(
    String label,
    String value,
    IconData icon,
  ) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon),
        const SizedBox(height: 6),
        Text(
          value,
          style: const TextStyle(
            fontSize: 22,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(label),
      ],
    );
  }

  Widget _buildSearchAndSort() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              key: const Key('product_search'),
              onChanged: controller.setQuery,
              decoration: const InputDecoration(
                labelText: 'Search products',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<ProductSort>(
              key: const Key('product_sort'),
              initialValue: controller.sort,
              decoration: const InputDecoration(
                labelText: 'Sort products',
                border: OutlineInputBorder(),
              ),
              items: [
                for (final option in ProductSort.values)
                  DropdownMenuItem(
                    value: option,
                    child: Text(option.label),
                  ),
              ],
              onChanged: (value) {
                if (value != null) {
                  controller.setSort(value);
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProductCard(Product product) {
    final favorite = controller.isFavorite(product);

    return Card(
      key: Key('product_${product.id}'),
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          children: [
            CircleAvatar(
              child: Text(product.id.toString().substring(1)),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.name,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${formatPrice(product.price)}  •  '
                    'Rating ${product.rating.toStringAsFixed(1)}',
                  ),
                  Text(
                    'Product ID: ${product.id}',
                    style: Theme.of(context)
                        .textTheme
                        .bodySmall,
                  ),
                ],
              ),
            ),
            IconButton(
              key: Key('favorite_${product.id}'),
              tooltip: favorite
                  ? 'Remove from favorites'
                  : 'Add to favorites',
              onPressed: () {
                controller.toggleFavorite(product);
              },
              icon: Icon(
                favorite
                    ? Icons.favorite
                    : Icons.favorite_border,
                color: favorite ? Colors.red : null,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Understanding the Flutter UI

The UI uses AnimatedBuilder to listen to the controller.

When the user changes the search query or sorting option, the controller recalculates the visible product list and notifies listeners.

Favorite buttons update the favorite ID set.

The interface also demonstrates why domain equality should be independent of UI presentation.

Changing a product’s displayed price or name does not automatically change its logical identity.


Part 6: Automated Unit Tests

20. Test Equality, Hashing, and Comparable

Code Block Pro — test/product_test.dart

Language: Dart

import 'package:flutter_test/flutter_test.dart';

import 'package:smart_product_comparator_lab/models/product.dart';

void main() {
  const first = Product(
    id: 101,
    name: 'Laptop',
    price: 50000,
    rating: 4.5,
  );

  const sameId = Product(
    id: 101,
    name: 'Updated Laptop',
    price: 49000,
    rating: 4.7,
  );

  const different = Product(
    id: 102,
    name: 'Tablet',
    price: 20000,
    rating: 4.3,
  );

  test('Equality is reflexive', () {
    expect(first == first, isTrue);
  });

  test('Same ID produces equality', () {
    expect(first, equals(sameId));
  });

  test('Different IDs are not equal', () {
    expect(first == different, isFalse);
  });

  test('Equal objects have equal hash codes', () {
    expect(first.hashCode, sameId.hashCode);
  });

  test('HashSet removes duplicate IDs', () {
    final products = <Product>{
      first,
      sameId,
      different,
    };

    expect(products.length, 2);
  });

  test('HashMap supports equivalent keys', () {
    final map = <Product, String>{
      first: 'Available',
    };

    expect(map[sameId], 'Available');
  });

  test('Comparable sorts by ID', () {
    final products = [
      different,
      first,
    ];

    products.sort();

    expect(products.first.id, 101);
    expect(products.last.id, 102);
  });

  test('Equal products compare as zero', () {
    expect(first.compareTo(sameId), 0);
  });

  test('copyWith preserves product identity', () {
    final updated = first.copyWith(price: 45000);

    expect(updated.id, first.id);
    expect(updated, first);
    expect(updated.price, 45000);
  });
}

These tests verify that equality, hashing, and natural ordering follow a consistent ID-based contract.


21. Test the Product Controller

Code Block Pro — test/product_controller_test.dart

Language: Dart

import 'package:flutter_test/flutter_test.dart';

import 'package:smart_product_comparator_lab/controllers/product_controller.dart';

void main() {
  late ProductController controller;

  setUp(() {
    controller = ProductController();
  });

  tearDown(() {
    controller.dispose();
  });

  test('Removes duplicate products', () {
    expect(controller.totalProducts, 5);
  });

  test('Searches products by name', () {
    controller.setQuery('speaker');

    expect(controller.visibleProducts.length, 1);
    expect(controller.visibleProducts.first.id, 103);
  });

  test('Sorts prices ascending', () {
    controller.setSort(ProductSort.priceAscending);

    final products = controller.visibleProducts;

    expect(products.first.price, 899);
    expect(products.last.price, 3999);
  });

  test('Sorts prices descending', () {
    controller.setSort(ProductSort.priceDescending);

    final products = controller.visibleProducts;

    expect(products.first.price, 3999);
    expect(products.last.price, 899);
  });

  test('Sorts ratings descending', () {
    controller.setSort(ProductSort.ratingDescending);

    expect(
      controller.visibleProducts.first.rating,
      4.7,
    );
  });

  test('Toggles favorites', () {
    final product = controller.visibleProducts.first;

    controller.toggleFavorite(product);
    expect(controller.favoriteCount, 1);

    controller.toggleFavorite(product);
    expect(controller.favoriteCount, 0);
  });

  test('Calculates average price', () {
    expect(controller.averagePrice, 2099);
  });

  test('Handles empty search results', () {
    controller.setQuery('unknown-product');

    expect(controller.visibleProducts, isEmpty);
  });
}

The tests cover deduplication, search, sorting, favorites, and summary calculations.


22. Flutter Widget Tests

Code Block Pro — test/widget_test.dart

Language: Dart

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:smart_product_comparator_lab/main.dart';

void main() {
  testWidgets('Displays product comparator app', (
    tester,
  ) async {
    await tester.pumpWidget(
      const SmartProductComparatorApp(),
    );

    expect(
      find.text('Smart Product Comparator'),
      findsOneWidget,
    );

    expect(
      find.text('Dart Equality & Sorting Lab'),
      findsOneWidget,
    );
  });

  testWidgets('Displays five unique products', (
    tester,
  ) async {
    await tester.pumpWidget(
      const SmartProductComparatorApp(),
    );

    expect(
      find.text('Products (5)'),
      findsOneWidget,
    );
  });

  testWidgets('Filters products by search', (
    tester,
  ) async {
    await tester.pumpWidget(
      const SmartProductComparatorApp(),
    );

    await tester.enterText(
      find.byKey(const Key('product_search')),
      'speaker',
    );

    await tester.pump();

    expect(
      find.text('Products (1)'),
      findsOneWidget,
    );

    expect(
      find.text('Bluetooth Speaker'),
      findsOneWidget,
    );
  });

  testWidgets('Displays empty results', (
    tester,
  ) async {
    await tester.pumpWidget(
      const SmartProductComparatorApp(),
    );

    await tester.enterText(
      find.byKey(const Key('product_search')),
      'not-found',
    );

    await tester.pump();

    expect(
      find.text('Products (0)'),
      findsOneWidget,
    );

    expect(
      find.text('No matching products found.'),
      findsOneWidget,
    );
  });

  testWidgets('Adds a product to favorites', (
    tester,
  ) async {
    await tester.pumpWidget(
      const SmartProductComparatorApp(),
    );

    final button = find.byKey(
      const Key('favorite_103'),
    );

    await tester.ensureVisible(button);
    await tester.tap(button);
    await tester.pump();

    final favoriteIcon = find.descendant(
      of: find.byKey(const Key('product_103')),
      matching: find.byIcon(Icons.favorite),
    );

    expect(favoriteIcon, findsOneWidget);
  });
}

These widget tests validate initial rendering, search behavior, empty states, and favorite interactions.


23. Run the Application and Tests

Run the application:

flutter run

Run all automated tests:

flutter test

Run static analysis:

flutter analyze

Format the source files:

dart format lib test

The code is provided as a complete project example, but it has not been executed in this session. Verify it with your installed Flutter SDK before publishing the application as tested.


Part 7: Advanced Equality Patterns

24. Identity-Based vs Value-Based Models

Not every Dart class should use value equality.

Consider a database connection object.

Two connections may have identical configuration settings but represent different active resources.

Treating them as equal based only on configuration could be incorrect.

On the other hand, a coordinate value object is naturally defined by its coordinates.

final class Coordinate {
  final double latitude;
  final double longitude;

  const Coordinate(this.latitude, this.longitude);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Coordinate &&
          latitude == other.latitude &&
          longitude == other.longitude;

  @override
  int get hashCode =>
      Object.hash(latitude, longitude);
}

This model represents value equality.

Choose equality semantics based on the meaning of the object in your domain.


25. Equality and Immutable Flutter State

Immutable models are especially useful in Flutter.

Suppose a user updates a product price.

Rather than modifying an existing object, create a new instance.

final updatedProduct = product.copyWith(
  price: 1499,
);

This makes state transitions more predictable.

However, value equality alone does not automatically notify widgets or trigger rebuilds.

The state-management mechanism still needs to publish or notify changes.

For example, a ChangeNotifier controller calls:

notifyListeners();

Other architectures may emit new states through Streams, notifiers, or framework-specific providers.

Equality and state notification are related but separate concerns.


26. Equality and Flutter Keys

Flutter uses keys to help match widgets across rebuilds.

A ValueKey<T> uses its value’s equality behavior.

For example:

ValueKey<int>(product.id)

is a straightforward choice for a product list when IDs are unique.

Using a full mutable product object as a key can be problematic if its equality semantics are not stable.

For dynamic lists, prefer stable identifiers.

Also remember that widget keys must be unique among siblings where required.


27. Deep Collection Equality

Consider:

final first = [1, 2, 3];
final second = [1, 2, 3];

print(first == second); // false

Dart lists do not use structural equality by default.

If you need to compare collection contents, you can implement the comparison explicitly.

For more complex nested structures, the collection package provides utilities such as ListEquality, SetEquality, MapEquality, and DeepCollectionEquality.

Use these when structural equality is part of your domain requirements.

Do not assume Object.hashAll() alone makes nested collections equal.


28. Floating-Point Equality

Floating-point calculations can introduce rounding differences.

For example:

final result = 0.1 + 0.2;

print(result == 0.3);

The comparison may be false because binary floating-point values cannot represent every decimal fraction exactly.

For numerical algorithms, tolerance-based comparisons may be appropriate.

For financial calculations, consider representing minor currency units as integers or using a suitable decimal arithmetic strategy.

Do not automatically apply approximate equality to hash-based value objects without carefully defining a consistent equivalence relation and hash contract.


29. Comparable and Stable Sorting

Dart’s list sorting API does not promise stable ordering for elements that compare as equal.

If you need deterministic results, include tie-breakers.

For example:

products.sort((a, b) {
  final ratingResult =
      b.rating.compareTo(a.rating);

  if (ratingResult != 0) {
    return ratingResult;
  }

  return a.id.compareTo(b.id);
});

This produces a predictable ordering when multiple products share the same rating.

The same technique works for prices, dates, names, and priorities.


Part 8: Common Mistakes

30. Equality and Sorting Mistakes to Avoid

Mistake 1: Overriding == Without hashCode

Always implement a compatible hash code when overriding equality.

Mistake 2: Assuming Hash Codes Are Unique

Different objects may share the same hash code.

Mistake 3: Using Mutable Fields in Hash Keys

Changing equality fields after insertion can break hash-based lookups.

Mistake 4: Comparing Lists with == for Their Contents

Ordinary Dart lists use identity-based equality.

Mistake 5: Treating compareTo() as Equality

Sorting equivalence and object equality are not automatically identical.

Mistake 6: Forgetting Sorting Tie-Breakers

Use secondary comparisons when deterministic ordering matters.

Mistake 7: Using Approximate Floating-Point Equality Carelessly

Approximate comparisons require careful mathematical and domain design.

Mistake 8: Using hashCode as a Database ID

Hash codes are not persistent unique identifiers.

Mistake 9: Making Every Domain Class a Value Object

Some classes represent entities or resources whose identity matters.

Mistake 10: Skipping Equality Contract Tests

Test reflexivity, symmetry, transitivity, hashing, and comparison consistency where applicable.


Part 9: Frequently Asked Questions

31. Dart Equality, hashCode & Comparable FAQs

1. What is object equality in Dart?

Object equality determines whether two values should be considered equal according to their equality implementation.

2. What is the difference between == and identical()?

== invokes equality behavior, while identical() checks object identity.

3. Why do two objects with identical fields sometimes compare as unequal?

Ordinary Dart class instances use identity-based equality unless their class defines another equality contract.

4. Can I override the equality operator?

Yes, using operator ==.

5. Why must I override hashCode?

Equal objects must produce equal hash codes for hash-based collections to work correctly.

6. Are hash codes unique?

No. Hash collisions are possible.

7. What does Object.hash() do?

It combines multiple values into a hash code.

8. What does Object.hashAll() do?

It hashes an iterable sequence of values.

9. Does Object.hashAll() provide deep equality?

No. It computes a hash; it does not redefine equality.

10. What is a value object?

An object whose equality is based on the values that define it rather than its individual identity.

11. Should value objects be immutable?

Generally, yes. Immutability helps preserve consistent equality and hashing.

12. How does HashSet remove duplicates?

It uses hash codes and equality to determine whether an equivalent element is already present.

13. Can custom objects be Map keys?

Yes, provided their equality and hash code behavior is appropriate.

14. What is Comparable in Dart?

An interface used to define natural ordering through compareTo().

15. What does compareTo() return?

A negative, zero, or positive integer indicating relative order.

16. What is a Comparator?

A function that compares two values for a particular sorting operation.

17. Can I sort custom Dart objects?

Yes, by implementing Comparable or passing a comparator to sort().

18. Does compareTo() have to agree with ==?

For a natural ordering used with equality-sensitive ordered structures, consistency is strongly recommended. A custom comparator may deliberately group distinct values for a specific sort.

19. Does Dart List use deep equality?

No. Ordinary lists use identity-based equality.

20. How can I compare nested collections?

Use explicit structural comparisons or suitable collection equality utilities.

21. Can equality affect Flutter widget keys?

Yes. ValueKey uses the equality behavior of its value.

22. Can equality improve Flutter state management?

It can help identify meaningful value changes, but state notification and rebuilding still depend on the chosen architecture.

23. Should I use hashCode as a persistent ID?

No.

24. Why is floating-point equality difficult?

Binary floating-point arithmetic can introduce rounding differences.

25. Are equality and Comparable useful in production Flutter apps?

Yes. They are fundamental for reliable domain models, collection behavior, sorting, and application state.


32. Conclusion

Dart equality, hashCode, and Comparable are foundational concepts for reliable application architecture.

Equality determines whether two objects represent the same logical value or entity.

Hash codes support efficient collection operations.

Comparable defines natural ordering.

Custom comparators provide flexible sorting strategies.

When these concepts are combined with immutable models and well-designed state management, Flutter applications become more predictable and easier to test.

In this tutorial, we built a complete Flutter Smart Product Comparator Lab featuring:

  • Immutable product models.
  • ID-based equality.
  • Consistent hash codes.
  • Product deduplication.
  • Multiple sorting strategies.
  • Favorites management.
  • Material 3 UI.
  • Unit tests.
  • Widget tests.

The key takeaway: Equality, hashing, and ordering must express the same domain rules consistently.

Choosing those rules deliberately is more important than simply overriding a few Dart methods.


What’s Next in the Flutter Tutorials Series?

Flutter Article 30: Dart Regular Expressions (RegExp) Explained — Validation, Search, Parsing & Practical Flutter Examples (2026 Guide)

The next tutorial will explore regular expressions, matching, capturing groups, input validation, search highlighting, and safe text-processing patterns in Flutter.

Continue learning at:

https://moiks.com/blog

Official Documentation and References

  1. Dart Object API — https://api.dart.dev/dart-core/Object-class.html
  2. Dart Comparable API — https://api.dart.dev/dart-core/Comparable-class.html
  3. Dart Comparator API — https://api.dart.dev/dart-core/Comparator.html
  4. Dart List API — https://api.dart.dev/dart-core/List-class.html
  5. Dart Set API — https://api.dart.dev/dart-core/Set-class.html
  6. Dart HashSet API — https://api.dart.dev/dart-collection/HashSet-class.html
  7. Dart HashMap API — https://api.dart.dev/dart-collection/HashMap-class.html
  8. Dart Effective Dart — https://dart.dev/effective-dart
  9. Flutter State Management — https://docs.flutter.dev/data-and-backend/state-mgmt
  10. Flutter Testing — https://docs.flutter.dev/testing/overview

Moiks Developer Blog — Practical Flutter, Dart, Android, and iOS development tutorials.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment