Dart Flutter Tips

Sorting collections

Instead of using the 'compare' in 'sort' every time, you can override a method 'compareTo' in your object.
Plague Fox
Sorting collections
Photo by Jan Antonin Kolar / Unsplash

Instead of using the compare in sort every time, you can override a method compareTo in your object.

void main() {
  final sortedArray = <A>[A(3), A(1), A(2)]..sort();
  print(sortedArray); // <A>[A(1), A(2), A(3)]
}

class A with Comparabte<A> {
  const A(this.id);

  final int id;

  @override
  int compareTo(A other) => id.compareTo(other.id);
  
  @override
  String toString() => 'A($id)';
}
Share
Comments
More from Plague Fox
Safe Resource Cleanup with Closure Chains
Dart Flutter Article

Safe Resource Cleanup with Closure Chains

Dart has no defer, no RAII, no scope guards. When multi-step async initialization fails midway, you need to unwind only what was set up — in reverse order, crash-safe. Here's a 6-line closure chain pattern that gives you transactional init, safe teardown, and cancellation support for free.
Plague Fox 5 min read

Plague Fox

Engineer by day, fox by night. Talks about Flutter & Dart.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Plague Fox.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.