DartBasic 2 min read

Dart lists and sorting: manage an inventory shortlist

Add, filter, sort and copy a list without accidentally changing the original order.

On this page

Inventory data is often displayed in several orders: original import order, alphabetical order and a restock shortlist. Make it clear which list owns which order. A list is ordered and indexable; sorting it is a mutation, not a new sorted view.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
void main() {
  final products = ['Keyboard', 'Monitor', 'Cable'];
  final display = [...products]..sort();
  final shortlist = display.where((name) => name.length <= 5).toList();
  print(products.join(', '));
  print(display.join(', '));
  print('Shortlist: ${shortlist.join(', ')}');
  final snapshot = List<String>.unmodifiable(products);
  print('Snapshot contains ${snapshot.length} products.');
}

Follow the data and control flow

The spread creates a new list before the cascade invokes sort. The source therefore remains Keyboard, Monitor, Cable, while the display list becomes alphabetical. Filtering returns an iterable; toList materializes the shortlist at this point.

An unmodifiable list prevents changing that list’s structure. It does not make mutable objects stored inside it deeply immutable. Use indexing only after checking a valid range; an empty list has no first element. Choose a set when uniqueness matters more than position.

A mistake to avoid

Writing final display = products..sort() aliases the same list and sorts the original. final prevents rebinding a variable; it does not freeze the object’s contents. Similarly, sorting repeatedly in a frequently called getter can add unnecessary work and unexpected side effects.

Practice and verification

Add a duplicate name and an empty string. Decide which are valid inventory labels before filtering. Create a length-based comparator with an alphabetical tie-breaker and verify the original list still preserves import order.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.