Question #134EasyDart Basics

What is predicate matching - give some example in dart?

#dart

Answer

Overview

Predicate matching in Dart refers to using a predicate — a function that takes a value and returns

text
bool
— to filter, test, or match elements in collections. A predicate
text
bool Function(T)
expresses a condition.


Basic Predicate with Collections

dart
final numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// where() — filter using predicate
final evens = numbers.where((n) => n.isEven).toList();
print(evens); // [2, 4, 6, 8, 10]

final largeOdds = numbers.where((n) => n.isOdd && n > 5).toList();
print(largeOdds); // [7, 9]

// any() — true if at least one matches
final hasNegative = numbers.any((n) => n < 0);
print(hasNegative); // false

// every() — true if all match
final allPositive = numbers.every((n) => n > 0);
print(allPositive); // true

// firstWhere() — first matching element
final firstBig = numbers.firstWhere((n) => n > 7, orElse: () => -1);
print(firstBig); // 8

Predicate as Typedef

dart
typedef Predicate<T> = bool Function(T value);

// Reusable predicates
Predicate<int> isEven = (n) => n % 2 == 0;
Predicate<int> isPositive = (n) => n > 0;
Predicate<String> isEmail = (s) => s.contains('@') && s.contains('.');

// Generic filter function using predicate
List<T> filter<T>(List<T> items, Predicate<T> predicate) {
  return items.where(predicate).toList();
}

final evens = filter([1, 2, 3, 4, 5], isEven); // [2, 4]
final valid = filter(['a@b.com', 'invalid', 'x@y.z'], isEmail);

Combining Predicates

dart
// Combine predicates with and / or
Predicate<int> combine(Predicate<int> a, Predicate<int> b) =>
    (n) => a(n) && b(n);

final isEvenAndPositive = combine((n) => n.isEven, (n) => n > 0);
print([2,1, 0, 1, 2, 3, 4].where(isEvenAndPositive).toList()); // [2, 4]

Predicate with Custom Objects

dart
class Product {
  final String name;
  final double price;
  final String category;
  Product(this.name, this.price, this.category);
}

final products = [
  Product('iPhone', 999.99, 'Electronics'),
  Product('Book', 14.99, 'Education'),
  Product('Headphones', 199.99, 'Electronics'),
];

// Predicate filtering
final affordable = products.where((p) => p.price < 200).toList();
final electronics = products.where((p) => p.category == 'Electronics').toList();
final expensiveElectronics = products
    .where((p) => p.category == 'Electronics' && p.price > 500)
    .toList();

Pattern Matching as Predicate (Dart 3)

dart
// switch expression with predicate-like guards
String classify(int n) => switch (n) {
  0 => 'zero',
  int x when x < 0 => 'negative',
  int x when x.isEven => 'positive even',
  _ => 'positive odd',
};

Predicate = a function returning bool. Use

text
where()
,
text
any()
,
text
every()
,
text
firstWhere()
with predicate lambdas for expressive, readable collection operations.